VOOZH about

URL: https://www.geeksforgeeks.org/dsa/construct-bst-from-given-preorder-traversal-using-stack/

⇱ Construct BST from given preorder traversal using Stack - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Construct BST from given preorder traversal using Stack

Last Updated : 23 Jul, 2025

Given preorder traversal of a binary search tree, construct the BST.
For example, if the given traversal is {10, 5, 1, 7, 40, 50}, then the output should be root of following tree. 
 

 10
 / \
 5 40
 / \ \
1 7 50 

We have discussed O(n^2) and O(n) recursive solutions in the previous post. Following is a stack based iterative solution that works in O(n) time.

  1. Create an empty stack.
  2. Make the first value as root. Push it to the stack.
  3. Keep on popping while the stack is not empty and the next value is greater than stack's top value. Make this value as the right child of the last popped node. Push the new node to the stack.
  4. If the next value is less than the stack's top value, make this value as the left child of the stack's top node. Push the new node to the stack.
  5. Repeat steps 2 and 3 until there are items remaining in pre[]. 

Implementation:


Output
Inorder traversal of the constructed tree: 
1 5 7 10 40 50 

Time Complexity: O(n). The complexity looks more from first look. If we take a closer look, we can observe that every item is pushed and popped only once. So at most 2n push/pop operations are performed in the main loops of constructTree(). Therefore, time complexity is O(n).

Auxiliary Space: O(n)

Comment
Article Tags: