![]() |
VOOZH | about |
Given the root of a Binary Search Tree, we need to insert a new node with given value in the BST. All the nodes have distinct values in the BST and we may assume that the the new value to be inserted is not present in BST.
Example:
A new key is inserted at the position that maintains the BST property. We start from the root and move downward: if the key is smaller, go left; if larger, go right. We continue until we find an unoccupied spot where the node can be placed without violating the BST property, and insert it there as a new leaf.
22 12 30 8 20 N 30 N N 15 N N N
Time Complexity: O(h)
Auxiliary Space: O(h), due to recursive stack.
Instead of using recursion, we can also implement the insertion operation iteratively using a while loop. Below is the implementation using a while loop, using the same idea as above.
22 12 30 8 20 N 30 N N 15 N N N
Time complexity: O(h), where h is the height of the tree.
Auxiliary space: O(1)
Related Links: