Construct the BST (Binary Search Tree) from its given level order traversal.
Examples:
Input : {7, 4, 12, 3, 6, 8, 1, 5, 10}
Output : BST:
7
/ \
4 12
/ \ /
3 6 8
/ / \
1 5 10
Approach :
The idea is to make a struct element NodeDetails which contains a pointer to the node , minimum data and maximum data of the ancestor.Now perform the steps as follows:
- Push the root node to the queue of type NodeDetails.
- Extract NodeDetails of a node from the queue and compare them with the minimum and maximum values.
- Check whether there are more elements in the arr[] and arr[i] can be left child of ‘temp.ptr’ or not .
- Check whether there are more elements in the arr[] and arr[i] can be right child of ‘temp.ptr’ or not .
- End the loop when the queue becomes empty.
Below is the C++ implementation of the above approach
C++
// C++ program to construct BST // using level order traversal #include <bits/stdc++.h> using namespace std; // Node structure of a binary tree struct Node { int data; Node* right; Node* left; Node(int x) { data = x; right = NULL; left = NULL; } }; // Structure formed to store the // details of the ancestor struct NodeDetails { Node* ptr; int min, max; }; // Function for the preorder traversal void preorderTraversal(Node* root) { if (!root) return; cout << root->data << " "; // Traversing left child preorderTraversal(root->left); // Traversing right child preorderTraversal(root->right); } // Function to make a new node // and return its pointer Node* getNode(int data) { Node* temp = new Node(0); temp->data = data; temp->left = NULL; temp->right = NULL; return temp; } // Function to construct the BST Node* constructBst(int arr[], int n) { if (n == 0) return NULL; Node* root; queue<NodeDetails> q; // index variable to // access array elements int i = 0; // Node details for the // root of the BST NodeDetails newNode; newNode.ptr = getNode(arr[i++]); newNode.min = INT_MIN; newNode.max = INT_MAX; q.push(newNode); // Getting the root of the BST root = newNode.ptr; // Until there are no more // elements in arr[] while (i != n) { // Extracting NodeDetails of a // node from the queue NodeDetails temp = q.front(); q.pop(); // Check whether there are more elements // in the arr[] and arr[i] can be // left child of 'temp.ptr' or not if (i < n && (arr[i] < temp.ptr->data && arr[i] > temp.min)) { // Create NodeDetails for newNode // and add it to the queue newNode.ptr = getNode(arr[i++]); newNode.min = temp.min; newNode.max = temp.ptr->data; q.push(newNode); // Make this 'newNode' as left child // of 'temp.ptr' temp.ptr->left = newNode.ptr; } // Check whether there are more elements // in the arr[] and arr[i] can be // right child of 'temp.ptr' or not if (i < n && (arr[i] > temp.ptr->data && arr[i] < temp.max)) { // Create NodeDetails for newNode // and add it to the queue newNode.ptr = getNode(arr[i++]); newNode.min = temp.ptr->data; newNode.max = temp.max; q.push(newNode); // Make this 'newNode' as right // child of 'temp.ptr' temp.ptr->right = newNode.ptr; } } // Root of the required BST return root; } // Driver code int main() { int n = 9; int arr[n] = { 7, 4, 12, 3, 6, 8, 1, 5, 10 }; Node* root = constructBst(arr, n); preorderTraversal(root); return 0; } |
7 4 3 1 6 5 12 8 10
Time Complexity for C++ Code O(N)
Here is another approach using Recursion to construct BST. Below is Python implementation for the same –
Python3
# Python implementation to construct a BST # from its level order traversal import math # node of a BST class Node: def __init__(self,data): self.data = data self.left = None self.right = None # function to print the inorder traversal def preorderTraversal( root): if (root == None): return None print(root.data,end = " ") preorderTraversal(root.left) preorderTraversal(root.right) # function to get a new node def getNode( data): # Allocate memory newNode = Node(data) # put in the data newNode.data = data newNode.left = None newNode.right = None return newNode # function to construct a BST from # its level order traversal def LevelOrder(root , data): if(root == None): root = getNode(data) return root if(data <= root.data): root.left = LevelOrder(root.left, data) else: root.right = LevelOrder(root.right, data) return root def constructBst( arr, n): if(n == 0): return None root = None for i in range(0,n): root = LevelOrder(root , arr[i]) return root # Driver code if __name__=='__main__': arr = [7, 4, 12, 3, 6, 8, 1, 5, 10] n = len(arr) root = constructBst(arr, n) root = preorderTraversal(root) # This code is contributed by Srathore |
7 4 3 1 6 5 12 8 10
Time Complexity for Python Code O(N log(N))
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Construct BST from its given level order traversal
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Build Binary Tree from BST such that it's level order traversal prints sorted data
- Level order traversal of Binary Tree using Morris Traversal
- Connect Nodes at same Level (Level Order Traversal)
- Insertion in n-ary tree in given order and Level order traversal
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Flatten Binary Tree in order of Level Order Traversal
- Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
- Construct BST from given preorder traversal | Set 2
- Find Leftmost and Rightmost node of BST from its given preorder traversal
- Construct a complete binary tree from given array in level order fashion
- Find postorder traversal of BST from preorder traversal
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Check if the given array can represent Level Order Traversal of Binary Search Tree
- Deletion of a given node K in a Binary Tree using Level Order Traversal
- Construct the full k-ary tree from its preorder traversal
- Construct the Rooted tree by using start and finish time of its DFS traversal
- Construct a tree from Inorder and Level order traversals | Set 1
- Construct a tree from Inorder and Level order traversals | Set 2
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

