Reputation: 337
I'm following a book which explains how to delete nodes from a binary search tree, basically if we have this tree:
10
/ \
4 100
/ \
1 8
/ \
6 9
\
7
and we want to delete node 4, the book says I should:
thus we get
10
/ \
6 100
/ \
1 8
/ \
7 9
However I thought of another way to do this:
thus we get
10
/ \
8 100
/ \
6 9
/ \
1 7
Now I'd like to ask: I see that my solution produces (at least in this case) a slightly more unbalanced tree.
Is there a reason why I should use my book's one instead of my own? It seems my solution is easier (at least from my point of view) to implement but I'd prefer someone else to point out if I'm mistaken.
Upvotes: 0
Views: 1386
Reputation: 55609
The code for neither approach is particularly complex.
Your approach generally will produce a less balanced tree, as you're taking a subtree (1
's subtree) and moving it (possibly) very far down the tree.
With their approach, 7
's subtree moves up 1 node and no other subtrees move.
It may simply be that they hadn't considered your approach, or, if they had, they likely would've picked theirs, because the less balanced the tree is, the worse the performance of queries on it.
Although this discussion isn't particularly significant, as basic binary search trees are rarely used in practice - self-balancing ones are used instead (to which one can make a much stronger argument because of trying to maintain certain properties to keep the tree balanced).
Upvotes: 2
Reputation: 173
When your tree is unbalanced the time to traverse the tree increases and thus you lose some benefits of using a BST.
Upvotes: 0