VOOZH about

URL: https://www.geeksforgeeks.org/dsa/construct-a-binary-tree-from-string-with-bracket-representation-set-2/

⇱ Construct a Binary Tree from String with bracket representation | Set 2 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Construct a Binary Tree from String with bracket representation | Set 2

Last Updated : 23 Jul, 2025

Given a string s consisting of parentheses {'(' and ')'} and integers, the task is to construct a Binary Tree from it and print its Preorder traversal.

Examples:

Input: S = "1(2)(3)"
Output: 1 2 3
Explanation: The corresponding binary tree is as follows:
            1
          /   \                      
        2     3                       

Input: "4(2(3)(1))(6(5))"
Output: 4 2 3 1 6 5
Explanation:
The corresponding binary tree is as follows:

              4
           /     \                  
         2       6          
      /  \     /                        
   3    1   5                       

Recursive Approach: Refer to the previous article to solve the problem recursively. 
Time Complexity: O(N2
Auxiliary Space: O(N)


 

Approach: This problem can be solved using stack data structure. Follow the steps below to solve the problem:


 

  • Update the character at position 0 as root of the binary tree and initialize a stack stk.
  • Iterate in the range [1, N-1] using the variable i: 
    • If '(' is encountered, push the root to the stack stk.
    • Otherwise, if ')' is encountered update root as the topmost element of the stack and pop the topmost element.
    • Otherwise, if the character is a number, then, branch into the part that is null (left or right).
  • At the end of the above steps, return the root node of the binary tree.


 

Below is the implementation of the above approach:


 

 
 


Output: 
4 2 3 1 6 5

 


 

Time Complexity: O(N)
Auxiliary Space: O(N)


 

Comment