An important application of binary tree is their use in searching. Let us assume that each node in the tree is assigned a key value. In our examples, we will assume for simplicity that these are integers, although arbitrarily complex keys are allowed. We will also assume that all the keys are distinct, and deal with duplicates later.
The property that makes a binary tree into a binary search tree is that for every node, X, in the tree, the values of all the keys in the left subtree are smaller than the key value in X, and the values of all the keys in the right subtree are larger than the key value in X.
Notice that this implies that all the elements in the tree can be ordered in some consistent manner.
Insertion can be done in Binary Search Tree as follows:
Step 1:Strat from the root node.
Step 2:If the data to be inserted is x, compare it with the root value.
Step 2.1:If they are equal then just stop.
Step 2.2:If the data to be inserted is less than the root value then choose the left sub-tree.
Step 2.3If the data to be inserted is greater than the root value then choose the right sub-tree.
Step 3:Repeat step 2 until the value is properly positioned.
The above mechanism is clearly shown in the following Fig 1.
Case 2:Deleted node has exactly one child.
Case 3:Deleted node has Two children.
In case 1 we simply delete the node but in case 2 we replace the node with its child. In case 3 the deleted node is replaced by the in-order successor of the node. All three cases has been shown in the following Figure.
Source code
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.