VOOZH about

URL: https://www.geeksforgeeks.org/dsa/construct-bst-given-level-order-traversal/

⇱ Construct BST from its given level order traversal - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Construct BST from its given level order traversal

Last Updated : 4 May, 2026

Given an array arr[] representing the level order traversal of a BST, and we have to construct the BST from it.

Example:

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

πŸ‘ Construct-BST-from-its-given-level-order-traversal

[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.

Output
7 4 3 1 6 5 12 8 10 
Comment