GeeksforGeeks App
Open App
Browser
Continue

# Construct BST from its given level order traversal

Construct the BST (Binary Search Tree) from its given level order traversal.

Examples:

Input: arr[] = {7, 4, 12, 3, 6, 8, 1, 5, 10}
Output: BST:
7
/    \
4     12
/  \     /
3   6  8
/   /   \
1  5   10

## Construct BST from its given level order traversal Using Recursion:

The idea is to use recursion as the first element will always be the root of the tree and second element will be the left child and the third element will be the right child (if fall in the range), and so on for all the remaining elements.

Follow the steps below to solve the problem:

• First, pick the first element of the array and make it root.
• Pick the second element, if its value is smaller than the root node value make it left child,
• Else make it right child
• Now recursively call step (2) and step (3) to make a BST from its level Order Traversal.

Below is the implementation of the above approach:

## C++

 `// C++ implementation to construct a BST``// from its level order traversal``#include ` `using` `namespace` `std;` `// node of a BST``struct` `Node {``    ``int` `data;``    ``Node *left, *right;``};` `// function to get a new node``Node* getNode(``int` `data)``{``    ``// Allocate memory``    ``Node* newNode = (Node*)``malloc``(``sizeof``(Node));` `    ``// put in the data``    ``newNode->data = data;``    ``newNode->left = newNode->right = NULL;``    ``return` `newNode;``}` `// function to construct a BST from``// its level order traversal``Node* LevelOrder(Node* root, ``int` `data)``{``    ``if` `(root == NULL) {``        ``root = getNode(data);``        ``return` `root;``    ``}``    ``if` `(data <= root->data)``        ``root->left = LevelOrder(root->left, data);``    ``else``        ``root->right = LevelOrder(root->right, data);``    ``return` `root;``}` `Node* constructBst(``int` `arr[], ``int` `n)``{``    ``if` `(n == 0)``        ``return` `NULL;``    ``Node* root = NULL;` `    ``for` `(``int` `i = 0; i < n; i++)``        ``root = LevelOrder(root, arr[i]);` `    ``return` `root;``}` `// function to print the inorder traversal``void` `inorderTraversal(Node* root)``{``    ``if` `(!root)``        ``return``;` `    ``inorderTraversal(root->left);``    ``cout << root->data << ``" "``;``    ``inorderTraversal(root->right);``}` `// Driver program to test above``int` `main()``{``    ``int` `arr[] = { 7, 4, 12, 3, 6, 8, 1, 5, 10 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);` `    ``Node* root = constructBst(arr, n);` `    ``cout << ``"Inorder Traversal: "``;``    ``inorderTraversal(root);``    ``return` `0;``}`

## Java

 `// Java implementation to construct a BST``// from its level order traversal` `import` `java.io.*;` `class` `GFG {` `    ``// node of a BST``    ``static` `class` `Node {``        ``int` `data;``        ``Node left, right;``    ``};` `    ``// function to get a new node``    ``static` `Node getNode(``int` `data)``    ``{``        ``// Allocate memory``        ``Node newNode = ``new` `Node();` `        ``// put in the data``        ``newNode.data = data;``        ``newNode.left = newNode.right = ``null``;``        ``return` `newNode;``    ``}` `    ``// function to construct a BST from``    ``// its level order traversal``    ``static` `Node LevelOrder(Node root, ``int` `data)``    ``{``        ``if` `(root == ``null``) {``            ``root = getNode(data);``            ``return` `root;``        ``}``        ``if` `(data <= root.data)``            ``root.left = LevelOrder(root.left, data);``        ``else``            ``root.right = LevelOrder(root.right, data);``        ``return` `root;``    ``}` `    ``static` `Node constructBst(``int` `arr[], ``int` `n)``    ``{``        ``if` `(n == ``0``)``            ``return` `null``;``        ``Node root = ``null``;` `        ``for` `(``int` `i = ``0``; i < n; i++)``            ``root = LevelOrder(root, arr[i]);` `        ``return` `root;``    ``}` `    ``// function to print the inorder traversal``    ``static` `void` `inorderTraversal(Node root)``    ``{``        ``if` `(root == ``null``)``            ``return``;` `        ``inorderTraversal(root.left);``        ``System.out.print(root.data + ``" "``);``        ``inorderTraversal(root.right);``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String args[])``    ``{``        ``int` `arr[] = { ``7``, ``4``, ``12``, ``3``, ``6``, ``8``, ``1``, ``5``, ``10` `};``        ``int` `n = arr.length;` `        ``Node root = constructBst(arr, n);` `        ``System.out.print(``"Inorder Traversal: "``);``        ``inorderTraversal(root);``    ``}``}` `// This code is contributed by Arnab Kundu`

## 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 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`  `# Function to print the inorder traversal``def` `inorderTraversal(root):``    ``if` `(root ``=``=` `None``):``        ``return` `None` `    ``inorderTraversal(root.left)``    ``print``(root.data, end``=``" "``)``    ``inorderTraversal(root.right)`  `# Driver program``if` `__name__ ``=``=` `'__main__'``:` `    ``arr ``=` `[``7``, ``4``, ``12``, ``3``, ``6``, ``8``, ``1``, ``5``, ``10``]``    ``n ``=` `len``(arr)` `    ``root ``=` `constructBst(arr, n)` `    ``print``(``"Inorder Traversal: "``, end``=``"")``    ``root ``=` `inorderTraversal(root)`  `# This code is contributed by Srathore`

## C#

 `// C# implementation to construct a BST``// from its level order traversal``using` `System;` `class` `GFG {` `    ``// node of a BST``    ``public` `class` `Node {``        ``public` `int` `data;``        ``public` `Node left, right;``    ``};` `    ``// function to get a new node``    ``static` `Node getNode(``int` `data)``    ``{``        ``// Allocate memory``        ``Node newNode = ``new` `Node();` `        ``// put in the data``        ``newNode.data = data;``        ``newNode.left = newNode.right = ``null``;``        ``return` `newNode;``    ``}` `    ``// function to construct a BST from``    ``// its level order traversal``    ``static` `Node LevelOrder(Node root, ``int` `data)``    ``{``        ``if` `(root == ``null``) {``            ``root = getNode(data);``            ``return` `root;``        ``}` `        ``if` `(data <= root.data)``            ``root.left = LevelOrder(root.left, data);``        ``else``            ``root.right = LevelOrder(root.right, data);``        ``return` `root;``    ``}` `    ``static` `Node constructBst(``int``[] arr, ``int` `n)``    ``{``        ``if` `(n == 0)``            ``return` `null``;``        ``Node root = ``null``;` `        ``for` `(``int` `i = 0; i < n; i++)``            ``root = LevelOrder(root, arr[i]);` `        ``return` `root;``    ``}` `    ``// function to print the inorder traversal``    ``static` `void` `inorderTraversal(Node root)``    ``{``        ``if` `(root == ``null``)``            ``return``;` `        ``inorderTraversal(root.left);``        ``Console.Write(root.data + ``" "``);``        ``inorderTraversal(root.right);``    ``}` `    ``// Driver code``    ``public` `static` `void` `Main(String[] args)``    ``{``        ``int``[] arr = { 7, 4, 12, 3, 6, 8, 1, 5, 10 };``        ``int` `n = arr.Length;` `        ``Node root = constructBst(arr, n);` `        ``Console.Write(``"Inorder Traversal: "``);``        ``inorderTraversal(root);``    ``}``}` `// This code is contributed by Rajput-Ji`

## Javascript

 ``

Output

`Inorder Traversal: 1 3 4 5 6 7 8 10 12 `

Time Complexity: O(N * H), Where N is the number of nodes in the tree and H is the height of the tree
Auxiliary Space: O(N), N is the number of nodes in the Tree

## Construct BST from its given level order traversal Using Queue:

The idea is similar to what we do while finding the level order traversal of a binary tree using the queue. In this case, we maintain a queue that contains a pair of the Node class and an integer pair storing the range for each of the tree nodes.

Follow the below steps to Implement the above idea:

• Create an empty queue q<pair<Node*,pair<int,int>>> and push root and range from – infinite to  + infinite in q.
• Run for loop through the entire array containing the level order traversal
• Get the front of the queue and store its Node (in temp variable) and its range.
• If arr[i] can be a child of temp by checking the value is within the range.
• Check whether arr[i] can be a left child or right child of the Node by checking the condition of BST.
• If arr[i] can be a left child, we create a new Node and point it to the left child of temp.
• We update the range such that its new lower bound is the same as before and it’s new upper bound is the value of temp node.
• If arr[i] can be the right child, we create a new Node and point it to the right child of temp.
• We update the range such that it’s new lower bound is the value of temp node and its new upper bound is the same as before.
• Pop the temp node from the queue once the right child is set. This is because the temp node cannot have any more children.
• Else we pop out the node from the queue, decrement i and go ahead.
• Initialize temp_node = q.front() and print temp_node->data.
• Push temp_node’s children i.e. temp_node -> left then temp_node -> right to q
• Pop front node from q.
• Finally, return the head of the tree.

Below is the Implementation of the above approach:

## C++

 `// C++ implementation to construct a BST``// from its level order traversal` `#include ``using` `namespace` `std;` `// node of a BST``struct` `Node {``    ``int` `data;``    ``Node *left, *right;` `    ``Node(``int` `x)``    ``{``        ``data = x;``        ``right = NULL;``        ``left = NULL;``    ``}``};` `// Function to construct a BST from``// its level order traversal``Node* constructBst(``int` `arr[], ``int` `n)``{``    ``// Create queue to store the tree nodes``    ``queue > > q;` `    ``// If array is empty we return NULL``    ``if` `(n == 0)``        ``return` `NULL;` `    ``// Create root node and store a copy of it in head``    ``Node *root = ``new` `Node(arr[0]), *head = root;` `    ``// Push the root node and the initial range``    ``q.push({ root, { INT_MIN, INT_MAX } });` `    ``// Loop over the contents of arr to process all the``    ``// elements``    ``for` `(``int` `i = 1; i < n; i++) {` `        ``// Get the node and the range at the front of the``        ``// queue``        ``Node* temp = q.front().first;``        ``pair<``int``, ``int``> range = q.front().second;` `        ``// Check if arr[i] can be a child of the temp node``        ``if` `(arr[i] > range.first && arr[i] < range.second) {` `            ``// Check if arr[i] can be left child``            ``if` `(arr[i] < temp->data) {` `                  ``if``(temp->left != NULL){``                    ``//if temp already has a left child``                      ``//temp can have no more children``                      ``q.pop();``                      ``i--;``                      ``continue``;``                ``}``              ` `                ``// Set the left child and range``                ``temp->left = ``new` `Node(arr[i]);``                ``q.push({ temp->left,``                         ``{ range.first, temp->data } });``            ``}``            ``// Check if arr[i] can be left child``            ``else` `{` `                ``// Pop the temp node from queue, set the``                ``// right child and new range``                ``q.pop();``                ``temp->right = ``new` `Node(arr[i]);``                ``q.push({ temp->right,``                         ``{ temp->data, range.second } });``            ``}``        ``}``        ``else` `{` `            ``q.pop();``            ``i--;``        ``}``    ``}``    ``return` `head;``}` `// Function to print the inorder traversal``void` `inorderTraversal(Node* root)``{``    ``if` `(!root)``        ``return``;` `    ``inorderTraversal(root->left);``    ``cout << root->data << ``" "``;``    ``inorderTraversal(root->right);``}` `// Driver program to test above``int` `main()``{``    ``int` `arr[] = { 7, 4, 12, 3, 6, 8, 1, 5, 10 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);` `    ``Node* root = constructBst(arr, n);` `    ``cout << ``"Inorder Traversal: "``;``    ``inorderTraversal(root);``    ``return` `0;``}` `// This code is contributed by Rohit Iyer (rohit_iyer)`

## Java

 `// Java code for the above approach``import` `java.io.*;``import` `java.util.*;` `// Node of a BST``class` `Node {``    ``int` `data;``    ``Node left, right;` `    ``public` `Node(``int` `data)``    ``{``        ``this``.data = data;``        ``this``.left = ``null``;``        ``this``.right = ``null``;``    ``}``}` `public` `class` `GFG {` `    ``static` `class` `NodeRange {``        ``Node node;``        ``int` `min, max;` `        ``public` `NodeRange(Node node, ``int` `min, ``int` `max)``        ``{``            ``this``.node = node;``            ``this``.min = min;``            ``this``.max = max;``        ``}``    ``}` `    ``public` `static` `Node constructBst(``int``[] arr)``    ``{``        ``if` `(arr.length == ``0``)``            ``return` `null``;` `        ``// Create root node and store a copy of it in head``        ``Node root = ``new` `Node(arr[``0``]), head = root;` `        ``// Create queue to store the tree nodes``        ``Queue queue = ``new` `LinkedList<>();``        ``queue.add(``new` `NodeRange(root, Integer.MIN_VALUE,``                                ``Integer.MAX_VALUE));` `        ``for` `(``int` `i = ``1``; i < arr.length; i++) {``            ``NodeRange nr = queue.peek();` `            ``// Check if arr[i] can be a child of the temp``            ``// node``            ``if` `(arr[i] > nr.min && arr[i] < nr.max) {``                ``// Check if arr[i] can be left child``                ``if` `(arr[i] < nr.node.data) {``                    ``// Set the left child and range``                    ``nr.node.left = ``new` `Node(arr[i]);``                    ``queue.add(``new` `NodeRange(nr.node.left,``                                            ``nr.min,``                                            ``nr.node.data));``                ``}``                ``// Check if arr[i] can be right child``                ``else` `{``                    ``// Pop the temp node from queue, set the``                    ``// right child and new range``                    ``queue.remove();``                    ``nr.node.right = ``new` `Node(arr[i]);``                    ``queue.add(``new` `NodeRange(nr.node.right,``                                            ``nr.node.data,``                                            ``nr.max));``                ``}``            ``}``            ``else` `{``                ``queue.remove();``                ``i--;``            ``}``        ``}` `        ``return` `head;``    ``}` `    ``public` `static` `void` `inorderTraversal(Node root)``    ``{``        ``if` `(root == ``null``)``            ``return``;``        ``inorderTraversal(root.left);``        ``System.out.print(root.data + ``" "``);``        ``inorderTraversal(root.right);``    ``}` `    ``public` `static` `void` `main(String[] args)``    ``{``        ``int``[] arr = { ``7``, ``4``, ``12``, ``3``, ``6``, ``8``, ``1``, ``5``, ``10` `};``        ``Node root = constructBst(arr);` `        ``System.out.print(``"Inorder Traversal: "``);``        ``inorderTraversal(root);``    ``}``}` `// This code is contributed by sankar.`

## Python3

 `# Python implementation to construct a BST``# from its level order traversal` `# Importing essential libraries``from` `collections ``import` `deque` `# Node of a BST`  `class` `Node:``    ``def` `__init__(``self``, data):``        ``self``.data ``=` `data``        ``self``.left ``=` `None``        ``self``.right ``=` `None`  `def` `constructBst(arr, n):``    ``queue ``=` `deque()``    ``if` `n ``=``=` `0``:``        ``return` `None` `    ``# Create root node and store a copy of it in head``    ``root ``=` `Node(arr[``0``])``    ``head ``=` `root` `    ``# Push the root node and the initial range``    ``queue.append((root, (``-``float``(``"inf"``), ``float``(``"inf"``))))``    ``i ``=` `1` `    ``# Loop over the contents of arr to process all the elements using``    ``# while loop we may have to process atmost 2 child's``    ``while` `i < n:` `        ``# Get the node and the range at the front of the queue``        ``# and popout the leftmost element``        ``temp ``=` `queue[``0``][``0``]``        ``tempRange ``=` `queue[``0``][``1``]``        ``queue.popleft()` `        ``# Check if arr[i] can be left child and within range of it's parent data``        ``if` `(arr[i] < temp.data) ``and` `tempRange[``0``] < arr[i] < tempRange[``1``]:` `            ``# Set the left child and new range for the child``            ``temp.left ``=` `Node(arr[i])``            ``queue.append((temp.left, (tempRange[``0``], temp.data)))``            ``i ``+``=` `1` `        ``# Check if arr[i] can be right child and within range of it's parent data``        ``if` `arr[i] > temp.data ``and` `tempRange[``0``] < arr[i] < tempRange[``1``]:` `            ``# Set the right child and new range for the child``            ``temp.right ``=` `Node(arr[i])``            ``queue.append((temp.right, (temp.data, tempRange[``1``])))``            ``i ``+``=` `1``    ``return` `head`  `def` `inorderTraversal(root):``    ``if` `(root ``=``=` `None``):``        ``return` `None` `    ``inorderTraversal(root.left)``    ``print``(root.data, end``=``" "``)``    ``inorderTraversal(root.right)`  `# Driver program``if` `__name__ ``=``=` `'__main__'``:` `    ``arr ``=` `[``7``, ``4``, ``12``, ``3``, ``6``, ``8``, ``1``, ``5``, ``10``]``    ``n ``=` `len``(arr)` `    ``root ``=` `constructBst(arr, n)` `    ``print``(``"Inorder Traversal: "``)``    ``root ``=` `inorderTraversal(root)`  `# This code is contributed by Divyanshu Singh`

## C#

 `using` `System;``using` `System.Collections.Generic;` `// Node of a BST``class` `Node {``    ``public` `int` `data;``    ``public` `Node left;``    ``public` `Node right;` `    ``public` `Node(``int` `data)``    ``{``        ``this``.data = data;``        ``left = ``null``;``        ``right = ``null``;``    ``}``}` `class` `BST {``    ``public` `Node constructBst(``int``[] arr, ``int` `n)``    ``{``        ``var` `queue``            ``= ``new` `Queue > >();` `        ``if` `(n == 0)``            ``return` `null``;` `        ``// Create root node and store a copy of it in head``        ``var` `root = ``new` `Node(arr[0]);``        ``var` `head = root;` `        ``// Push the root node and the initial range``        ``queue.Enqueue(``            ``Tuple.Create(root, Tuple.Create(``int``.MinValue,``                                            ``int``.MaxValue)));``        ``int` `i = 1;` `        ``// Loop over the contents of arr to process all the``        ``// elements using while loop we may have to process``        ``// atmost 2 child's``        ``while` `(i < n) {``            ``// Get the node and the range at the front of``            ``// the queue and popout the leftmost element``            ``var` `temp = queue.Dequeue();``            ``var` `tempRange = temp.Item2;` `            ``// Check if arr[i] can be left child and within``            ``// range of it's parent data``            ``if` `(arr[i] < temp.Item1.data``                ``&& tempRange.Item1 < arr[i]``                ``&& arr[i] < tempRange.Item2) {``                ``// Set the left child and new range for the``                ``// child``                ``temp.Item1.left = ``new` `Node(arr[i]);``                ``queue.Enqueue(Tuple.Create(``                    ``temp.Item1.left,``                    ``Tuple.Create(tempRange.Item1,``                                 ``temp.Item1.data)));``                ``i++;``            ``}` `            ``// Check if arr[i] can be right child and within``            ``// range of it's parent data``            ``if` `(arr[i] > temp.Item1.data``                ``&& tempRange.Item1 < arr[i]``                ``&& arr[i] < tempRange.Item2) {``                ``// Set the right child and new range for the``                ``// child``                ``temp.Item1.right = ``new` `Node(arr[i]);``                ``queue.Enqueue(Tuple.Create(``                    ``temp.Item1.right,``                    ``Tuple.Create(temp.Item1.data,``                                 ``tempRange.Item2)));``                ``i++;``            ``}``        ``}``        ``return` `head;``    ``}` `    ``public` `void` `inorderTraversal(Node root)``    ``{``        ``if` `(root == ``null``)``            ``return``;` `        ``inorderTraversal(root.left);``        ``Console.Write(root.data + ``" "``);``        ``inorderTraversal(root.right);``    ``}` `    ``// Driver program``    ``public` `static` `void` `Main(``string``[] args)``    ``{` `        ``var` `arr = ``new` `int``[] { 7, 4, 12, 3, 6, 8, 1, 5, 10 };``        ``int` `n = arr.Length;` `        ``var` `bst = ``new` `BST();``        ``var` `root = bst.constructBst(arr, n);` `        ``Console.WriteLine(``"Inorder Traversal:"``);``        ``bst.inorderTraversal(root);``    ``}``}`

## Javascript

 `// Javascript code for the above approach``class Node {``    ``constructor(data) {``        ``this``.data = data;``        ``this``.left = ``null``;``        ``this``.right = ``null``;``    ``}``}` `function` `constructBst(arr) {``    ``if` `(arr.length === 0) ``return` `null``;` `    ``// Create root node and store a copy of it in head``    ``let root = ``new` `Node(arr[0]), head = root;` `    ``// Create queue to store the tree nodes``    ``let queue = [{ node: root, range: { min: Number.MIN_SAFE_INTEGER, max: Number.MAX_SAFE_INTEGER } }];` `    ``for` `(let i = 1; i < arr.length; i++) {``        ``let { node, range } = queue[0];` `        ``// Check if arr[i] can be a child of the temp node``        ``if` `(arr[i] > range.min && arr[i] < range.max) {``            ``// Check if arr[i] can be left child``            ``if` `(arr[i] < node.data) {``                ``// Set the left child and range``                ``node.left = ``new` `Node(arr[i]);``                ``queue.push({ node: node.left, range: { min: range.min, max: node.data } });``            ``}``            ``// Check if arr[i] can be left child``            ``else` `{``                ``// Pop the temp node from queue, set the right child and new range``                ``queue.shift();``                ``node.right = ``new` `Node(arr[i]);``                ``queue.push({ node: node.right, range: { min: node.data, max: range.max } });``            ``}``        ``}``        ``else` `{``            ``queue.shift();``            ``i--;``        ``}``    ``}` `    ``return` `head;``}` `function` `inorderTraversal(root) {``    ``if` `(!root) ``return``;``    ``inorderTraversal(root.left);``    ``console.log(root.data+``" "``);``    ``inorderTraversal(root.right);``}` `let arr = [7, 4, 12, 3, 6, 8, 1, 5, 10];``let root = constructBst(arr);` `console.log(``"Inorder Traversal: "``);``inorderTraversal(root);` `// This code is contributed by lokeshpotta20.`

Output

`Inorder Traversal: 1 3 4 5 6 7 8 10 12 `

Time Complexity: O(N), Visiting every node once.
Auxiliary Space: O(N), Using queue to store the nodes

This article is contributed by Nishant Balayan and Rohit Iyer. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

My Personal Notes arrow_drop_up