A binary search tree is an ordered tree, where the left child must only contain values smaller than the root and the right child must contain only values larger than the root. This makes searching for values in the tree much more efficient. Instead of potentially having to look at every single node to find some value, you simply compare it to the root. This means the number of comparisons you need to make is equivalent to the depth of the tree where that value is or would be if it were in the tree.
When deleting a value from a binary search tree, there are three cases to account for. The first, and simplest case is deleting a leaf (that is, a node with no children). When deleting a leaf, all you have to do is find that value in the tree, remove it and then replace it with an empty node. The second case is deleting an internal node with one child. This case requires finding and removing the value and then replacing it with its own child, where replacing it refers to giving its parent a new left or right. The final, and most complicated case, involves deleting an internal node with 2 children. In this case, you need to make sure you are replacing it with a value that is higher than everything on the left side and lower than everything on the right side. You are left with two options for what to do. You may either replace the node with the highest value on the left side, or with the lowest value on the right side. In class we learned to replace the node with the maximum node on the left side, because we had already defined a function which would return the maximum node in a tree. However, this is not the only way.
I can't say which method is better, because they appear to be about equivalent.



No comments:
Post a Comment