[Naive Approach] Using Recursion - O(n * h) space and O(n) space
The idea is to create an empty BST and insert each element from the level order array one by one using the BST insertion property, where smaller elements go to the left subtree and larger elements go to the right subtree.
Steps to solve the problem:
Start with an empty root node.
For each value in the level order array, insert it into the BST using the following rules:
If the current node is null, create a new node with the given value and return it.
If the value is smaller than the current nodeβs value, recursively insert it into the left subtree.
If the value is larger than the current nodeβs value, recursively insert it into the right subtree
Output
7 4 3 1 6 5 12 8 10
[Expected Approach] Using Level Order Traversal - O(n) time and O(n) space
The idea is to build the BST level by level using a queue, where each node carries a valid value range. New elements are inserted as left or right children only if they fall within the range, ensuring the BST property is maintained.
Steps to solve the problem:
Take the first element as root and push it into a queue with the value range (ββ, +β).
For each next element in the level order array, look at the front node and check whether it can be placed in its left or right subtree based on the valid range.
If it fits on the left, create the left child, assign range (low, node->data β 1), and push it to the queue.
If it fits on the right, create the right child, assign range (node->data + 1, high), and push it to the queue.
Continue this process until all elements are inserted and the BST is fully constructed.