Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Stack
  • Practice Stack
  • MCQs on Stack
  • Stack Tutorial
  • Stack Operations
  • Stack Implementations
  • Monotonic Stack
  • Infix to Postfix
  • Prefix to Postfix
  • Prefix to Infix
  • Advantages & Disadvantages
Open In App
Next Article:
Binary tree to string with brackets
Next article icon

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

Last Updated : 23 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

 

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Build a tree node having left and
// right pointers set to null initially
struct Node {
    Node* left;
    Node* right;
    int data;
 
    // Constructor to set the data of
    // the newly created tree node
    Node(int element)
    {
        data = element;
        this->left = nullptr;
        this->right = nullptr;
    }
};
 
// Utility function to print
// preorder traversal of the tree
void preorder(Node* root)
{
    if (!root)
        return;
 
    cout << root->data << " ";
    preorder(root->left);
    preorder(root->right);
}
 
// Function to construct a
// tree using bracket notation
Node* constructTree(string s)
{
 
    // First character is the root of the tree
    Node* root = new Node(s[0] - '0');
 
    // Stack used to store the
    // previous root elements
    stack<Node*> stk;
 
    // Iterate over remaining characters
    for (int i = 1; i < s.length(); i++) {
 
        // If current character is '('
        if (s[i] == '(') {
 
            // Push root into stack
            stk.push(root);
        }
 
        // If current character is ')'
        else if (s[i] == ')') {
 
            // Make root the top most
            // element in the stack
            root = stk.top();
 
            // Remove the top node
            stk.pop();
        }
 
        // If current character is a number
        else {
 
            // If left is null, then put the new
            // node to the left and move to the
            // left of the root
            if (root->left == nullptr) {
 
                Node* left = new Node(s[i] - '0');
                root->left = left;
                root = root->left;
            }
 
            // Otherwise, if right is null, then
            // put the new node to the right and
            // move to the right of the root
            else if (root->right == nullptr) {
 
                Node* right = new Node(s[i] - '0');
                root->right = right;
                root = root->right;
            }
        }
    }
 
    // Return the root
    return root;
}
 
// Driver code
int main()
{
    // Input
    string s = "4(2(3)(1))(6(5))";
 
    // Function calls
    Node* root = constructTree(s);
    preorder(root);
 
    return 0;
}
 
 

Java




// Java program for the above approach
import java.util.*;
public class Main
{
    // Class containing left and
    // right child of current
    // node and key value
    static class Node {
        
        public int data;
        public Node left, right;
        
        public Node(int element)
        {
            data = element;
            left = right = null;
        }
    }
     
    // Utility function to print
    // preorder traversal of the tree
    static void preorder(Node root)
    {
        if (root == null)
            return;
       
        System.out.print(root.data + " ");
        preorder(root.left);
        preorder(root.right);
    }
       
    // Function to construct a
    // tree using bracket notation
    static Node constructTree(String s)
    {
       
        // First character is the root of the tree
        Node root = new Node(s.charAt(0) - '0');
       
        // Stack used to store the
        // previous root elements
        Stack<Node> stk = new Stack<Node>();
       
        // Iterate over remaining characters
        for (int i = 1; i < s.length(); i++) {
       
            // If current character is '('
            if (s.charAt(i) == '(') {
       
                // Push root into stack
                stk.push(root);
            }
       
            // If current character is ')'
            else if (s.charAt(i) == ')') {
       
                // Make root the top most
                // element in the stack
                root = stk.peek();
       
                // Remove the top node
                stk.pop();
            }
       
            // If current character is a number
            else {
       
                // If left is null, then put the new
                // node to the left and move to the
                // left of the root
                if (root.left == null) {
       
                    Node left = new Node(s.charAt(i) - '0');
                    root.left = left;
                    root = root.left;
                }
       
                // Otherwise, if right is null, then
                // put the new node to the right and
                // move to the right of the root
                else if (root.right == null) {
       
                    Node right = new Node(s.charAt(i) - '0');
                    root.right = right;
                    root = root.right;
                }
            }
        }
       
        // Return the root
        return root;
    }
     
    public static void main(String[] args) {
        // Input
        String s = "4(2(3)(1))(6(5))";
       
        // Function calls
        Node root = constructTree(s);
        preorder(root);
    }
}
 
// This code is contributed by divyesh072019.
 
 

Python3




# Python program for the above approach
 
# Build a tree node having left and
# right pointers set to null initially
class Node:
    # Constructor to set the data of
    # the newly created tree node
    def __init__(self, element):
        self.data = element
        self.left = None
        self.right = None
 
# Utility function to print
# preorder traversal of the tree
def preorder(root):
    if (not root):
        return
 
    print(root.data, end = " ")
    preorder(root.left)
    preorder(root.right)
 
# Function to construct a
# tree using bracket notation
def constructTree(s):
 
    # First character is the root of the tree
    root = Node(ord(s[0]) - ord('0'))
 
    # Stack used to store the
    # previous root elements
    stk = []
 
    # Iterate over remaining characters
    for i in range(1,len(s)):
        # If current character is '('
        if (s[i] == '('):
 
            # Push root into stack
            stk.append(root)
 
        # If current character is ')'
        elif (s[i] == ')'):
 
            # Make root the top most
            # element in the stack
            root = stk[-1]
 
            # Remove the top node
            del stk[-1]
        # If current character is a number
        else:
 
            # If left is null, then put the new
            # node to the left and move to the
            # left of the root
            if (root.left == None):
 
                left = Node(ord(s[i]) - ord('0'))
                root.left = left
                root = root.left
 
            # Otherwise, if right is null, then
            # put the new node to the right and
            # move to the right of the root
            elif (root.right == None):
 
                right =  Node(ord(s[i]) - ord('0'))
                root.right = right
                root = root.right
 
    # Return the root
    return root
 
# Driver code
if __name__ == '__main__':
    # Input
    s = "4(2(3)(1))(6(5))"
 
    # Function calls
    root = constructTree(s)
    preorder(root)
 
# This code is contributed by mohit kumar 29.
 
 

C#




// C# program for the above approach
using System;
using System.Collections;
class GFG
{
     
    // Class containing left and
    // right child of current
    // node and key value
    class Node {
       
        public int data;
        public Node left, right;
       
        public Node(int element)
        {
            data = element;
            left = right = null;
        }
    }
     
    // Utility function to print
    // preorder traversal of the tree
    static void preorder(Node root)
    {
        if (root == null)
            return;
      
        Console.Write(root.data + " ");
        preorder(root.left);
        preorder(root.right);
    }
      
    // Function to construct a
    // tree using bracket notation
    static Node constructTree(string s)
    {
      
        // First character is the root of the tree
        Node root = new Node(s[0] - '0');
      
        // Stack used to store the
        // previous root elements
        Stack stk = new Stack();
      
        // Iterate over remaining characters
        for (int i = 1; i < s.Length; i++) {
      
            // If current character is '('
            if (s[i] == '(') {
      
                // Push root into stack
                stk.Push(root);
            }
      
            // If current character is ')'
            else if (s[i] == ')') {
      
                // Make root the top most
                // element in the stack
                root = (Node)(stk.Peek());
      
                // Remove the top node
                stk.Pop();
            }
      
            // If current character is a number
            else {
      
                // If left is null, then put the new
                // node to the left and move to the
                // left of the root
                if (root.left == null) {
      
                    Node left = new Node(s[i] - '0');
                    root.left = left;
                    root = root.left;
                }
      
                // Otherwise, if right is null, then
                // put the new node to the right and
                // move to the right of the root
                else if (root.right == null) {
      
                    Node right = new Node(s[i] - '0');
                    root.right = right;
                    root = root.right;
                }
            }
        }
      
        // Return the root
        return root;
    }
 
  // Driver code
  static void Main()
  {
     
    // Input
    string s = "4(2(3)(1))(6(5))";
  
    // Function calls
    Node root = constructTree(s);
    preorder(root);
  }
}
 
// This code is contributed by decode2207.
 
 

Javascript




<script>
    // Javascript program for the above approach  
    class Node
    {
        constructor(element) {
           this.left = null;
           this.right = null;
           this.data = element;
        }
    }
     
    // Utility function to print
    // preorder traversal of the tree
    function preorder(root)
    {
        if (root == null)
            return;
 
        document.write(root.data + " ");
        preorder(root.left);
        preorder(root.right);
    }
 
    // Function to construct a
    // tree using bracket notation
    function constructTree(s)
    {
 
        // First character is the root of the tree
        let root = new Node(s[0].charCodeAt() - '0'.charCodeAt());
 
        // Stack used to store the
        // previous root elements
        let stk = [];
 
        // Iterate over remaining characters
        for (let i = 1; i < s.length; i++) {
 
            // If current character is '('
            if (s[i] == '(') {
 
                // Push root into stack
                stk.push(root);
            }
 
            // If current character is ')'
            else if (s[i] == ')') {
 
                // Make root the top most
                // element in the stack
                root = stk[stk.length - 1];
 
                // Remove the top node
                stk.pop();
            }
 
            // If current character is a number
            else {
 
                // If left is null, then put the new
                // node to the left and move to the
                // left of the root
                if (root.left == null) {
 
                    let left = new Node(s[i].charCodeAt() - '0'.charCodeAt());
                    root.left = left;
                    root = root.left;
                }
 
                // Otherwise, if right is null, then
                // put the new node to the right and
                // move to the right of the root
                else if (root.right == null) {
 
                    let right = new Node(s[i].charCodeAt() - '0'.charCodeAt());
                    root.right = right;
                    root = root.right;
                }
            }
        }
 
        // Return the root
        return root;
    }
     
    // Input
    let s = "4(2(3)(1))(6(5))";
  
    // Function calls
    let root = constructTree(s);
    preorder(root);
 
// This code is contributed by divyeshrabadiya07.
</script>
 
 

 
 

Output: 
4 2 3 1 6 5

 

 

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

 



Next Article
Binary tree to string with brackets

M

manjukrishna
Improve
Article Tags :
  • DSA
  • Misc
  • Stack
  • Strings
  • Tree
  • Parentheses-Problems
Practice Tags :
  • Misc
  • Stack
  • Strings
  • Tree

Similar Reads

  • Mastering Bracket Problems for Competitive Programming
    Bracket problems in programming typically refer to problems that involve working with parentheses, and/or braces in expressions or sequences. It typically refers to problems related to the correct and balanced usage of parentheses, and braces in expressions or code. These problems often involve chec
    4 min read
  • Check if given Parentheses expression is balanced or not
    Given a string str of length N, consisting of '(' and ')' only, the task is to check whether it is balanced or not.Examples: Input: str = "((()))()()" Output: BalancedInput: str = "())((())" Output: Not Balanced Approach 1: Declare a Flag variable which denotes expression is balanced or not.Initiali
    9 min read
  • Valid Parentheses in an Expression
    Given a string s representing an expression containing various types of brackets: {}, (), and [], the task is to determine whether the brackets in the expression are balanced or not. A balanced expression is one where every opening bracket has a corresponding closing bracket in the correct order. Ex
    8 min read
  • Length of longest balanced parentheses prefix
    Given a string of open bracket '(' and closed bracket ')'. The task is to find the length of longest balanced prefix. Examples: Input : S = "((()())())((" Output : 10From index 0 to index 9, they are forming a balanced parentheses prefix.Input : S = "()(())((()"Output : 6 The idea is take value of o
    9 min read
  • Modify a numeric string to a balanced parentheses by replacements
    Given a numeric string S made up of characters '1', '2' and '3' only, the task is to replace characters with either an open bracket ( '(' ) or a closed bracket ( ')' ) such that the newly formed string becomes a balanced bracket sequence. Note: All occurrences of a character must be replaced by the
    10 min read
  • Check if the bracket sequence can be balanced with at most one change in the position of a bracket
    Given an unbalanced bracket sequence as a string str, the task is to find whether the given string can be balanced by moving at most one bracket from its original place in the sequence to any other position.Examples: Input: str = ")(()" Output: Yes As by moving s[0] to the end will make it valid. "(
    6 min read
  • Number of closing brackets needed to complete a regular bracket sequence
    Given an incomplete bracket sequence S. The task is to find the number of closing brackets ')' needed to make it a regular bracket sequence and print the complete bracket sequence. You are allowed to add the brackets only at the end of the given bracket sequence. If it is not possible to complete th
    7 min read
  • Minimum number of Parentheses to be added to make it valid
    Given a string S of parentheses '(' or ')' where, [Tex]0\leq len(S)\leq 1000 [/Tex]. The task is to find a minimum number of parentheses '(' or ')' (at any positions) we must add to make the resulting parentheses string is valid. Examples: Input: str = "())" Output: 1 One '(' is required at beginnin
    9 min read
  • Minimum bracket reversals to make an expression balanced
    Given an expression with only '}' and '{'. The expression may not be balanced. Find minimum number of bracket reversals to make the expression balanced. Examples: Input: s = "}{{}}{{{"Output: 3Explanation: We need to reverse minimum 3 brackets to make "{{{}}{}}". Input: s = "{{"Output: 1Explanation:
    15+ min read
  • Find the number of valid parentheses expressions of given length
    Given a number n, the task is to find the number of valid parentheses expressions of that length. Examples : Input: 2Output: 1 Explanation: There is only possible valid expression of length 2, "()"Input: 4Output: 2 Explanation: Possible valid expression of length 4 are "(())" and "()()" Input: 6Outp
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences