Binary Search Tree
Binary Search Tree
For a binary tree to be a binary search tree, the data of all the nodes in the left sub-tree of the root
node should be ≤≤ the data of the root. The data of all the nodes in the right subtree of the root node
should be >> the data of the root.
Example
Also, considering the root node with data=5data=5, its children also satisfy the specified ordering.
Similarly, the root node with data=19data=19 also satisfies this ordering. When recursive, all
subtrees satisfy the left and right subtree ordering.
Pre-order traversal
Post-order traversal
In-order traversal
Node with data=1data=1 does not have a left subtree. Hence, this node is processed.
Node with data=1data=1 does not have a right subtree. Hence, nothing is done.
inorder(1) gets completed and this function call is popped from the call stack.
Left subtree of node with data=5data=5 is completely processed. Hence, this node gets
processed.
Right subtree of this node with data=5data=5 is non-empty. Hence, the right subtree gets
processed now. 'inorder(6)' is then called.
Note
'inorder(6)' is only equivalent to saying inorder(pointer to node with data=6data=6). The notation
has been used for brevity.
Both the left and right subtrees of node with data=5data=5 have been completely processed.
Hence, inorder(5) is then completed.
The order in which BST in Fig. 1 is visited is: 1, 5, 6, 10, 17, 19. The in-order traversal of a BST
gives a sorted ordering of the data elements that are present in the BST. This is an important
property of a BST.
Insertion in BST
1. If the data of the root node is greater, and if a left subtree exists, then repeat step 1 with root
= root of left subtree. Else, insert element as left child of current root.
2. If the data of the root node is greater, and if a right subtree exists, then repeat step 2 with
root = root of right subtree. Else, insert element as right child of current root.
Implementation