VOOZH about

URL: https://www.geeksforgeeks.org/dsa/construct-a-special-tree-from-given-preorder-traversal/

⇱ Construct a special tree from given preorder traversal - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Construct a special tree from given preorder traversal

Last Updated : 23 Jul, 2025

Given an array pre[] that represents the Preorder traversal of a special binary tree where every node has either 0 or 2 children. One more array preLN[] is given which has only two possible values ā€˜L’ and ā€˜N’. The value ā€˜L’ in preLN[] indicates that the corresponding node in Binary Tree is a leaf node and the value ā€˜N’ indicates that the corresponding node is a non-leaf node. The task is to construct the tree from the given two arrays.

Example:

Input:  pre[] = {10, 30, 20, 5, 15},  preLN[] = {'N', 'N', 'L', 'L', 'L'}
Output:

šŸ‘ Construct-a-special-tree-from-given-preorder-traversal

[Expected Approach] Using Pre-Order Traversal - O(n) Time and O(h) Space

The first element in pre[] will always be root. So we can easily figure out the root. If the left subtree is empty, the right subtree must also be empty, and the preLN[] entry for root must be ā€˜L’. We can simply create a node and return it. If the left and right subtrees are not empty, then recursively call for left and right subtrees and link the returned nodes to root.  


Output
20 30 5 10 15 

[Alternate Approach] Using Stack - O(n) Time and O(h) Space

The idea is to use a stack to implement pre-order traversal and construct the binary tree and return the root node.

Step by step implementation:

  1. As the Pre-order Traversal is given, so we first create the root node and insert it into an empty stack.
  2. Traverse the given pre-order traversal.
    1. Create the node corresponding to the current value.
    2. Check the top node in the stack:
      • If left of top node is null, then set the current node as left of top node.
      • Else, right of top node is null, then set the current node as right of top node and pop the top node.
    3. If the present node is not a leaf node, push node into the stack.
  3. Return the root of the constructed tree.

Output
20 30 5 10 15 

Related article:

Comment
Article Tags: