Construct Binary Tree from String with bracket representation
Last Updated : 21 May, 2025
Comments
Improve
Suggest changes
2 Likes
Like
Report
Given a string consisting of parenthesis and integers, representing a binary tree. The task is to construct a binary tree from this string.
The string contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root's value and a pair of parenthesis contains a child binary tree with the same structure. Always start to construct the left child node of the parent first if it exists.
In a binary tree string representation, each part begins with a number representing the node's value, followed by at most two pairs of parentheses. The first pair of parentheses after a number contains the complete left subtree of that node (if it exists), and the second pair of parentheses contains the complete right subtree (if it exists). Each subtree follows the same pattern recursively, making it a self-similar structure.
[Naive Approach] Using Recursion - O(n^2) time and O(n) space:
The idea is to recursively parse the string by first extracting the root value (which could be multiple digits) and then finding matching pairs of parentheses that enclose the left and right subtrees.
For each subtree enclosed in parentheses, we find its corresponding closing parenthesis using a counter (incrementing for '(' and decrementing for ')'), which helps us identify the correct substring for the left child.
Once we have the left subtree's closing index, we can process the right subtree starting two positions after (to skip the closing parenthesis and opening parenthesis of right subtree).
This process continues recursively until we either encounter an empty substring (base case) or process all characters, effectively building the tree from root to leaves.
C++
//Driver Code Starts// C++ program to construct a binary // tree from the given string#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};//Driver Code Ends// function to return the index of close parenthjsintfindIndex(stringstr,inti,intj){if(i>j)return-1;intcnt=0;for(intk=i;k<=j;k++){if(str[k]=='(')cnt++;elseif(str[k]==')'){cnt--;if(cnt==0)returnk;}}return-1;}// function to construct tree from stringNode*constructTreeRecur(stringstr,inti,intj){// Base caseif(i>j)returnnullptr;intval=0;// In case the value is having more than 1 digitwhile(i<=j&&str[i]>='0'&&str[i]<='9'){val*=10;val+=(str[i]-'0');i++;}// new rootNode*root=newNode(val);intindex=-1;// if next char is '(' find the index of// its complement ')'if(i<=j&&str[i]=='(')index=findIndex(str,i,j);// if index foundif(index!=-1){// call for left subtreeroot->left=constructTreeRecur(str,i+1,index-1);// call for right subtreeroot->right=constructTreeRecur(str,index+2,j-1);}returnroot;}Node*treeFromString(stringstr){Node*root=constructTreeRecur(str,0,str.length()-1);returnroot;}//Driver Code StartsvoidlevelOrder(Node*root){if(root==nullptr){cout<<"N ";return;}queue<Node*>qq;qq.push(root);while(!qq.empty()){Node*curr=qq.front();qq.pop();if(curr==nullptr){cout<<"N ";continue;}cout<<(curr->data)<<" ";qq.push(curr->left);qq.push(curr->right);}}intmain(){stringstr="4(2(3)(1))(6(5))";Node*root=treeFromString(str);levelOrder(root);}//Driver Code Ends
↔
// function to return the index of close parenthjs
//Driver Code Starts// Java program to construct a binary // tree from the given stringimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{//Driver Code Ends// function to return the index of close parenthesisstaticintfindIndex(Stringstr,inti,intj){if(i>j)return-1;intcnt=0;for(intk=i;k<=j;k++){if(str.charAt(k)=='(')cnt++;elseif(str.charAt(k)==')'){cnt--;if(cnt==0)returnk;}}return-1;}// function to construct tree from stringstaticNodeconstructTreeRecur(Stringstr,inti,intj){// Base caseif(i>j)returnnull;intval=0;// In case the value is having more than 1 digitwhile(i<=j&&Character.isDigit(str.charAt(i))){val*=10;val+=(str.charAt(i)-'0');i++;}// new rootNoderoot=newNode(val);intindex=-1;// if next char is '(' find the index of// its complement ')'if(i<=j&&str.charAt(i)=='(')index=findIndex(str,i,j);// if index foundif(index!=-1){// call for left subtreeroot.left=constructTreeRecur(str,i+1,index-1);// call for right subtreeroot.right=constructTreeRecur(str,index+2,j-1);}returnroot;}staticNodetreeFromString(Stringstr){returnconstructTreeRecur(str,0,str.length()-1);}//Driver Code StartsstaticvoidlevelOrder(Noderoot){if(root==null){System.out.print("N ");return;}Queue<Node>queue=newLinkedList<>();queue.add(root);while(!queue.isEmpty()){Nodecurr=queue.poll();if(curr==null){System.out.print("N ");continue;}System.out.print(curr.data+" ");queue.add(curr.left);queue.add(curr.right);}}publicstaticvoidmain(String[]args){String[]str={"4(2(3)(1))(6(5))"};Noderoot=treeFromString(str[0]);levelOrder(root);}}//Driver Code Ends
Python
#Driver Code Starts# Python program to construct a binary # tree from the given stringfromcollectionsimportdequeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None#Driver Code Ends# function to return the index of close parenthesisdeffindIndex(str,i,j):ifi>j:return-1cnt=0forkinrange(i,j+1):ifstr[k]=='(':cnt+=1elifstr[k]==')':cnt-=1ifcnt==0:returnkreturn-1# function to construct tree from stringdefconstructTreeRecur(str,i,j):# Base caseifi>j:returnNoneval=0# In case the value is having more than 1 digitwhilei<=jandstr[i].isdigit():val*=10val+=int(str[i])i+=1# new rootroot=Node(val)index=-1# if next char is '(' find the index of# its complement ')'ifi<=jandstr[i]=='(':index=findIndex(str,i,j)# if index foundifindex!=-1:# call for left subtreeroot.left=constructTreeRecur(str,i+1,index-1)# call for right subtreeroot.right=constructTreeRecur(str,index+2,j-1)returnrootdeftreeFromString(str):returnconstructTreeRecur(str,0,len(str)-1)#Driver Code StartsdeflevelOrder(root):ifrootisNone:print("N ",end="")returnqueue=deque([root])whilequeue:curr=queue.popleft()ifcurrisNone:print("N ",end="")continueprint(curr.data,end=" ")queue.append(curr.left)queue.append(curr.right)if__name__=="__main__":str=["4(2(3)(1))(6(5))"]root=treeFromString(str[0])levelOrder(root)#Driver Code Ends
C#
//Driver Code Starts// C# program to construct a binary // tree from the given stringusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{//Driver Code Ends// function to return the index of close parenthesisstaticintfindIndex(stringstr,inti,intj){if(i>j)return-1;intcnt=0;for(intk=i;k<=j;k++){if(str[k]=='(')cnt++;elseif(str[k]==')'){cnt--;if(cnt==0)returnk;}}return-1;}// function to construct tree from stringstaticNodeconstructTreeRecur(stringstr,inti,intj){// Base caseif(i>j)returnnull;intval=0;// In case the value is having more than 1 digitwhile(i<=j&&char.IsDigit(str[i])){val*=10;val+=(str[i]-'0');i++;}// new rootNoderoot=newNode(val);intindex=-1;// if next char is '(' find the index of// its complement ')'if(i<=j&&str[i]=='(')index=findIndex(str,i,j);// if index foundif(index!=-1){// call for left subtreeroot.left=constructTreeRecur(str,i+1,index-1);// call for right subtreeroot.right=constructTreeRecur(str,index+2,j-1);}returnroot;}staticNodetreeFromString(stringstr){returnconstructTreeRecur(str,0,str.Length-1);}//Driver Code StartsstaticvoidlevelOrder(Noderoot){if(root==null){Console.Write("N ");return;}Queue<Node>queue=newQueue<Node>();queue.Enqueue(root);while(queue.Count>0){Nodecurr=queue.Dequeue();if(curr==null){Console.Write("N ");continue;}Console.Write(curr.data+" ");queue.Enqueue(curr.left);queue.Enqueue(curr.right);}}staticvoidMain(){string[]str={"4(2(3)(1))(6(5))"};Noderoot=treeFromString(str[0]);levelOrder(root);}}//Driver Code Ends
JavaScript
//Driver Code Starts// JavaScript program to construct a binary // tree from the given stringclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}//Driver Code Ends// function to return the index of close parenthesisfunctionfindIndex(str,i,j){if(i>j)return-1;letcnt=0;for(letk=i;k<=j;k++){if(str[k]==='(')cnt++;elseif(str[k]===')'){cnt--;if(cnt===0)returnk;}}return-1;}// function to construct tree from stringfunctionconstructTreeRecur(str,i,j){if(i>j)returnnull;letval=0;while(i<=j&&!isNaN(str[i])){val=val*10+(str[i]-'0');i++;}letroot=newNode(val);letindex=-1;if(i<=j&&str[i]==='(')index=findIndex(str,i,j);if(index!==-1){root.left=constructTreeRecur(str,i+1,index-1);root.right=constructTreeRecur(str,index+2,j-1);}returnroot;}functiontreeFromString(str){returnconstructTreeRecur(str,0,str.length-1);}//Driver Code StartsfunctionlevelOrder(root){if(root===null){process.stdout.write("N ");return;}letqueue=[];queue.push(root);while(queue.length>0){letcurr=queue.shift();if(curr===null){process.stdout.write("N ");continue;}process.stdout.write(curr.data+" ");queue.push(curr.left);queue.push(curr.right);}}letstr=["4(2(3)(1))(6(5))"];letroot=treeFromString(str[0]);levelOrder(root);//Driver Code Ends
Output
4 2 6 3 1 5 N N N N N N N
[Expected Approach] Using Pre-Order Traversal - O(n) time and O(n) space
The idea is to traverse the string sequentially using a single index passed by reference, constructing the tree in a preorder manner (root-left-right) where we first extract the root value by parsing consecutive digits, then recursively build the left subtree if we encounter an opening parenthesis, and finally build the right subtree if another opening parenthesis exists after completing the left subtree construction.
Step by step approach:
Maintain a single index that traverses through the string from left to right.
When encountering digits, parse them to form the complete node value and create a new node with the parsed value.
If an opening parenthesis '(' is found, increment index and recursively build left subtree. After left subtree is built and index is incremented past closing parenthesis, check for another opening parenthesis.
If second opening parenthesis exists, increment index and recursively build right subtree.
Return the constructed node which serves as root for its subtree
C++
//Driver Code Starts// C++ program to construct a binary // tree from the given string#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};//Driver Code Ends// Recursive function to construct// tree using preorder traversal.Node*preOrder(int&i,string&s){// If substring is empty, return null.if(s[i]==')')returnnullptr;// Find the value of root node.intval=0;while(i<s.length()&&s[i]!='('&&s[i]!=')'){intdigit=s[i]-'0';i++;val=val*10+digit;}// Create the root node.Node*root=newNode(val);// If left subtree existsif(i<s.length()&&s[i]=='('){i++;root->left=preOrder(i,s);i++;}// If right subtree existsif(i<s.length()&&s[i]=='('){i++;root->right=preOrder(i,s);i++;}// Return the root node.returnroot;}// function to construct tree from stringNode*treeFromString(strings){inti=0;returnpreOrder(i,s);}//Driver Code StartsvoidlevelOrder(Node*root){if(root==nullptr){cout<<"N ";return;}queue<Node*>qq;qq.push(root);while(!qq.empty()){Node*curr=qq.front();qq.pop();if(curr==nullptr){cout<<"N ";continue;}cout<<(curr->data)<<" ";qq.push(curr->left);qq.push(curr->right);}}intmain(){stringstr="4(2(3)(1))(6(5))";Node*root=treeFromString(str);levelOrder(root);}//Driver Code Ends
↔
// Recursive function to construct
// tree using preorder traversal.
Node*preOrder(int&i, string&s) {
// If substring is empty, return null.
if (s[i]==')') returnnullptr;
// Find the value of root node.
intval=0;
while (i<s.length() &&s[i]!='('&&s[i]!=')') {
intdigit=s[i]-'0';
i++;
val=val*10+digit;
}
// Create the root node.
Node*root=newNode(val);
// If left subtree exists
if (i<s.length() &&s[i]=='(') {
i++;
root->left=preOrder(i, s);
i++;
}
// If right subtree exists
if (i<s.length() &&s[i]=='(') {
i++;
root->right=preOrder(i, s);
i++;
}
// Return the root node.
returnroot;
}
// function to construct tree from string
Node*treeFromString(strings){
inti=0;
returnpreOrder(i, s);
}
↔
Java
//Driver Code Starts// Java program to construct a binary // tree from the given stringimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{//Driver Code Ends// Recursive function to construct// tree using preorder traversal.staticNodepreOrder(int[]i,Strings){// If substring is empty, return null.if(s.charAt(i[0])==')')returnnull;// Find the value of root node.intval=0;while(i[0]<s.length()&&s.charAt(i[0])!='('&&s.charAt(i[0])!=')'){intdigit=s.charAt(i[0])-'0';i[0]++;val=val*10+digit;}// Create the root node.Noderoot=newNode(val);// If left subtree existsif(i[0]<s.length()&&s.charAt(i[0])=='('){i[0]++;root.left=preOrder(i,s);i[0]++;}// If right subtree existsif(i[0]<s.length()&&s.charAt(i[0])=='('){i[0]++;root.right=preOrder(i,s);i[0]++;}// Return the root node.returnroot;}staticNodetreeFromString(Strings){int[]i={0};returnpreOrder(i,s);}//Driver Code StartsstaticvoidlevelOrder(Noderoot){if(root==null){System.out.print("N ");return;}Queue<Node>queue=newLinkedList<>();queue.add(root);while(!queue.isEmpty()){Nodecurr=queue.poll();if(curr==null){System.out.print("N ");continue;}System.out.print(curr.data+" ");queue.add(curr.left);queue.add(curr.right);}}publicstaticvoidmain(String[]args){Stringstr="4(2(3)(1))(6(5))";Noderoot=treeFromString(str);levelOrder(root);}}//Driver Code Ends
Python
#Driver Code Starts# Python program to construct a binary # tree from the given stringfromcollectionsimportdequeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None#Driver Code Ends# Recursive function to construct# tree using preorder traversal.defpreOrder(i,s):# If substring is empty, return null.ifs[i[0]]==')':returnNone# Find the value of root node.val=0whilei[0]<len(s)ands[i[0]]notin('(',')'):digit=int(s[i[0]])i[0]+=1val=val*10+digit# Create the root node.root=Node(val)# If left subtree existsifi[0]<len(s)ands[i[0]]=='(':i[0]+=1root.left=preOrder(i,s)i[0]+=1# If right subtree existsifi[0]<len(s)ands[i[0]]=='(':i[0]+=1root.right=preOrder(i,s)i[0]+=1# Return the root node.returnrootdeftreeFromString(s):i=[0]returnpreOrder(i,s)#Driver Code StartsdeflevelOrder(root):ifrootisNone:print("N ",end="")returnqueue=deque([root])whilequeue:curr=queue.popleft()ifcurrisNone:print("N ",end="")continueprint(curr.data,end=" ")queue.append(curr.left)queue.append(curr.right)if__name__=="__main__":str_val="4(2(3)(1))(6(5))"root=treeFromString(str_val)levelOrder(root)#Driver Code Ends
C#
//Driver Code Starts// C# program to construct a binary // tree from the given stringusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{//Driver Code Ends// Recursive function to construct// tree using preorder traversal.staticNodepreOrder(refinti,strings){// If substring is empty, return null.if(s[i]==')')returnnull;// Find the value of root node.intval=0;while(i<s.Length&&s[i]!='('&&s[i]!=')'){intdigit=s[i]-'0';i++;val=val*10+digit;}// Create the root node.Noderoot=newNode(val);// If left subtree existsif(i<s.Length&&s[i]=='('){i++;root.left=preOrder(refi,s);i++;}// If right subtree existsif(i<s.Length&&s[i]=='('){i++;root.right=preOrder(refi,s);i++;}// Return the root node.returnroot;}staticNodetreeFromString(strings){inti=0;returnpreOrder(refi,s);}//Driver Code StartsstaticvoidlevelOrder(Noderoot){if(root==null){Console.Write("N ");return;}Queue<Node>queue=newQueue<Node>();queue.Enqueue(root);while(queue.Count>0){Nodecurr=queue.Dequeue();if(curr==null){Console.Write("N ");continue;}Console.Write(curr.data+" ");queue.Enqueue(curr.left);queue.Enqueue(curr.right);}}staticvoidMain(string[]args){stringstr="4(2(3)(1))(6(5))";Noderoot=treeFromString(str);levelOrder(root);}}//Driver Code Ends
JavaScript
//Driver Code Starts// JavaScript program to construct a binary // tree from the given stringclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}//Driver Code EndsfunctionpreOrder(i,s){if(s[i[0]]===')')returnnull;letval=0;while(i[0]<s.length&&s[i[0]]!=='('&&s[i[0]]!==')'){letdigit=s[i[0]]-'0';i[0]++;val=val*10+digit;}letroot=newNode(val);if(i[0]<s.length&&s[i[0]]==='('){i[0]++;root.left=preOrder(i,s);i[0]++;}if(i[0]<s.length&&s[i[0]]==='('){i[0]++;root.right=preOrder(i,s);i[0]++;}returnroot;}functiontreeFromString(s){leti=[0];returnpreOrder(i,s);}//Driver Code StartsfunctionlevelOrder(root){if(root===null){process.stdout.write("N ");return;}letqueue=[];queue.push(root);while(queue.length>0){letcurr=queue.shift();if(curr===null){process.stdout.write("N ");continue;}process.stdout.write(curr.data+" ");queue.push(curr.left);queue.push(curr.right);}}letstr="4(2(3)(1))(6(5))";letroot=treeFromString(str);levelOrder(root);//Driver Code Ends
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
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.