Construct a string consisting of parenthesis and integers from a binary tree using the preorder traversing method. The null node needs to be represented by empty parenthesis pair “()”. Remove all the empty parenthesis pairs that don’t affect the one-to-one mapping relationship between the string and the original binary tree.
Examples:
Input:
Output: "1(2(4)(5))(3)" Explanation: Originally it needs to be "1(2(4)(5))(3()())", but we need to remove all the unnecessary empty parenthesis pairs. So, it will be "1(2(4)(5))(3)".
The idea is to do the preorder traversal of the given Binary Tree along with this, we need to make use of braces at appropriate positions. But, we also need to make sure that we remove the unnecessary braces. We print the current node and call for the left and the right children of the node in that order(if they exist).
For every node encountered, the following cases are possible.
Case 1: Both the left child and the right child exist for the current node. In this case, we need to put the braces () around both the left child's preorder traversal output and the right child's preorder traversal output.
Case 2: None of the left or the right child exist for the current node. In this case, considering empty braces for the null left and right children is redundant. Hence, we need not put braces for any of them.
Case 3: Only the left child exists for the current node. Putting empty braces for the right child in this case is unnecessary while considering the preorder traversal. This is because the right child will always come after the left child in the preorder traversal. Thus, omitting the empty braces for the right child also leads to same mapping between the string and the binary tree.
Case 4: Only the right child exists for the current node. In this case, we need to consider the empty braces for the left child. This is because, during the preorder traversal, the left child needs to be considered first. Thus, to indicate that the child following the current node is a right child we need to put a pair of empty braces for the left child.
Below is the implementation of above approach:
C++
// C++ Program to convert Binary tree// to string with brackets#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intval){data=val;left=nullptr;right=nullptr;}};// Function to construct string from binary treevoidtreeToString(Node*root,string&str){if(root==nullptr)return;// push the root data as characterstr.push_back(root->data+'0');// if leaf node, then returnif(!root->left&&!root->right)return;// for left subtreestr.push_back('(');treeToString(root->left,str);str.push_back(')');// only if right child is present to // avoid extra parenthesisif(root->right){str.push_back('(');treeToString(root->right,str);str.push_back(')');}}intmain(){// Let us construct below tree// 1// / \ // 2 3// / \ \ // 4 5 6 Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->right=newNode(6);stringstr="";treeToString(root,str);cout<<str;}
Java
// Java Program to convert Binary tree// to string with bracketsclassNode{intdata;Nodeleft,right;Node(intval){data=val;left=null;right=null;}}classGfG{// Function to construct string from binary treestaticvoidtreeToString(Noderoot,StringBuilderstr){// base caseif(root==null){return;}// push the root data as characterstr.append(root.data);// if leaf node, then returnif(root.left==null&&root.right==null){return;}// for left subtreestr.append('(');treeToString(root.left,str);str.append(')');// only if right child is present to // avoid extra parenthesisif(root.right!=null){str.append('(');treeToString(root.right,str);str.append(')');}}publicstaticvoidmain(String[]args){// Let us construct below tree// 1// / \// 2 3// / \ \// 4 5 6 Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.right=newNode(6);StringBuilderstr=newStringBuilder();treeToString(root,str);System.out.println(str.toString());}}
Python
# Python Program to convert Binary tree# to string with bracketsclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Function to construct string from binary treedeftreeToString(root,result):# base caseifrootisNone:return# push the root data as characterresult.append(str(root.data))# if leaf node, then returnifnotroot.leftandnotroot.right:return# for left subtreeresult.append('(')treeToString(root.left,result)result.append(')')# only if right child is present to # avoid extra parenthesisifroot.right:result.append('(')treeToString(root.right,result)result.append(')')if__name__=="__main__":# Let us construct below tree# 1# / \# 2 3# / \ \# 4 5 6 root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.right=Node(6)result=[]treeToString(root,result)print("".join(result))
C#
// C# Program to convert Binary tree to // string with bracketsusingSystem;usingSystem.Text;classNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=null;right=null;}}classGfG{// Function to construct string from binary treestaticvoidTreeToString(Noderoot,StringBuilderstr){// base caseif(root==null)return;// push the root data as characterstr.Append(root.data);// if leaf node, then returnif(root.left==null&&root.right==null)return;// for left subtreestr.Append('(');TreeToString(root.left,str);str.Append(')');// only if right child is present to // avoid extra parenthesisif(root.right!=null){str.Append('(');TreeToString(root.right,str);str.Append(')');}}staticvoidMain(string[]args){// Let us construct below tree// 1// / \// 2 3// / \ \// 4 5 6 Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.right=newNode(6);StringBuilderstr=newStringBuilder();TreeToString(root,str);Console.WriteLine(str.ToString());}}
JavaScript
// JavaScript Program to convert Binary // tree to string with bracketsclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Function to construct string from binary treefunctiontreeToString(root,result){// base caseif(root===null)return;// push the root data as characterresult.push(root.data.toString());// if leaf node, then returnif(!root.left&&!root.right)return;// for left subtreeresult.push('(');treeToString(root.left,result);result.push(')');// only if right child is present to // avoid extra parenthesisif(root.right){result.push('(');treeToString(root.right,result);result.push(')');}}// Let us construct below tree// 1// / \// 2 3// / \ \// 4 5 6 letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.right=newNode(6);letresult=[];treeToString(root,result);console.log(result.join(''));
Output
1(2(4)(5))(3()(6))
Time complexity: O(n) where n is the number of nodes in Binary Tree. Auxiliary Space: O(h), where h is height of tree.