Insertion
In a binary search tree, all elements in the right subtree of a node are greater than the node and all elements in the left subtree of the node are less than the node. Accordingly, if the element to be inserted is greater than the node, it is inserted in its right subtree, and if it is less than the node, insertion is done in the left subtree. For example, in the tree shown below, for insertion of 5 :
1. 5 < 10; so 5 will be in the left subtree of 10.
2. 5 < 6; so 5 will be in the left subtree of 6.
3. 5 > 4; so 5 will be in the right subtree of 4.
4. Since the right subtree of 4 is empty, 5 will be inserted there, i.e., as a right child of 4.
|
Insertion in a Binary Search Tree |
The helper function create(val) used in the above code creates a new node with 'val' as the node value, and NULL left and right children. Here's the create(int) function :
Related links :
Introduction to trees
Binary Search Trees : Traversal