arakakivl
arakakivl

Reputation: 347

Deleting a node from a search binary tree

So I was studying data structures and I finally get to start to understanding binary trees. The resource that I'm using and some others articles establish some rules for removing a node from a search binary tree, and they are:

I made a very basic image on paint to what I'm trying to understand. Well, looks like I'm the only that is not understanding this, so I think I have lost some concept or anything.enter image description here

Upvotes: 0

Views: 248

Answers (1)

btilly
btilly

Reputation: 46389

Your example search tree is not a search tree. Because you go right from 50 and get to numbers that can be both smaller than (eg 45) and bigger than (eg 65) 50.

After you fix that, there are three cases of note.

  1. The removed node is a leaf, delete it.
  2. The removed node only has one branch. Replace where it went with that branch.
  3. You need to merge the branches into a new tree, the root of whom goes where the deleted node was.

Complicating this in practice is the fact that we don't want trees to become unbalanced. Because unbalanced trees are not efficient to search. So sometimes you want to not simply attach, but also to rotate the tree around to get a better balanced result.

https://stackoverflow.com/a/75453554/585411 has the last time I wrote tree code. It does all of that. Perhaps studying that code will help you figure this out?

Upvotes: 2

Related Questions