Binary tree to string with brackets - GeeksforGeeks

30 Jun, 2021
Construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way. The null node needs to be represented by empty parenthesis pair “()”. Omit 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 : Preorder: [1, 2, 3, 4]
       1
     /   \
    2     3
   /    
  4     
Output: "1(2(4))(3)"
Explanation: Originally it needs to be "1(2(4)
())(3()())", but we need to omit all the 
unnecessary empty parenthesis pairs. 
And it will be "1(2(4))(3)".

Input : Preorder: [1, 2, 3, null, 4]
       1
     /   \
    2     3
     \  
      4 
Output: "1(2()(4))(3)"
 
This is opposite of Construct Binary Tree from String with bracket representationThe 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 omit the unnecessary braces. We print the current node and call the same given function 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, as shown in the figure below, 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. As the figure below shows, 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.  
 
C++
Java
Python3
C#
Javascript
/* C++ program to construct string from binary tree*/#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left   child and a pointer to right child */struct Node {    int data;    Node *left, *right;}; /* Helper function that allocates a new node */Node* newNode(int data){    Node* node = (Node*)malloc(sizeof(Node));    node->data = data;    node->left = node->right = NULL;    return (node);} // Function to construct string from binary treevoid treeToString(Node* root, string& str){    // bases case    if (root == NULL)        return;     // push the root data as character    str.push_back(root->data + '0');     // if leaf node, then return    if (!root->left && !root->right)        return;     // for left subtree    str.push_back('(');    treeToString(root->left, str);    str.push_back(')');     // only if right child is present to    // avoid extra parenthesis    if (root->right) {        str.push_back('(');        treeToString(root->right, str);        str.push_back(')');    }} // Driver Codeint main(){    /* Let us construct below tree                1               / \              2   3             / \   \            4   5   6    */    struct 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);    string str = "";    treeToString(root, str);    cout << str;}
// Java program to construct string from binary treeclass GFG{     /* A binary tree node has data, pointer to leftchild and a pointer to right child */static class Node{    int data;    Node left, right;};static String str; /* Helper function that allocates a new node */static Node newNode(int data){    Node node = new Node();    node.data = data;    node.left = node.right = null;    return (node);} // Function to construct string from binary treestatic void treeToString(Node root){    // bases case    if (root == null)        return;     // push the root data as character    str += (Character.valueOf((char)           (root.data + '0')));     // if leaf node, then return    if (root.left == null && root.right == null)        return;     // for left subtree    str += ('(');    treeToString(root.left);    str += (')');     // only if right child is present to    // avoid extra parenthesis    if (root.right != null)    {        str += ('(');        treeToString(root.right);        str += (')');    }} // Driver Codepublic static void main(String[] args){         /* 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);    str = "";    treeToString(root);    System.out.println(str);}} // This code is contributed by 29AjayKumar
# Python3 program to construct string from binary tree # A binary tree node has data, pointer to left# child and a pointer to right childclass Node:    def __init__(self, data):        self.data = data        self.left = None        self.right = None # Function to construct string from binary treedef treeToString(root: Node, string: list):     # base case    if root is None:        return     # push the root data as character    string.append(str(root.data))     # if leaf node, then return    if not root.left and not root.right:        return     # for left subtree    string.append('(')    treeToString(root.left, string)    string.append(')')     # only if right child is present to    # avoid extra parenthesis    if root.right:        string.append('(')        treeToString(root.right, string)        string.append(')') # Driver Codeif __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)    string = []    treeToString(root, string)    print(''.join(string)) # This code is contributed by# sanjeev2552
// C# program to construct string from binary treeusing System;     class GFG{     /* A binary tree node has data, pointer to leftchild and a pointer to right child */public class Node{    public int data;    public Node left, right;};static String str; /* Helper function that allocates a new node */static Node newNode(int data){    Node node = new Node();    node.data = data;    node.left = node.right = null;    return (node);} // Function to construct string from binary treestatic void treeToString(Node root){    // bases case    if (root == null)        return;     // push the root data as character    str += (char)(root.data + '0');     // if leaf node, then return    if (root.left == null && root.right == null)        return;     // for left subtree    str += ('(');    treeToString(root.left);    str += (')');     // only if right child is present to    // avoid extra parenthesis    if (root.right != null)    {        str += ('(');        treeToString(root.right);        str += (')');    }} // Driver Codepublic static void Main(String[] args){         /* 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);    str = "";    treeToString(root);    Console.WriteLine(str);}} // This code is contributed by Princi Singh
<script>     // JavaScript program to construct string from binary tree         class Node    {        constructor(data) {           this.left = null;           this.right = null;           this.data = data;        }    }     let str;       /* Helper function that allocates a new node */    function newNode(data)    {        let node = new Node(data);        return (node);    }     // Function to construct string from binary tree    function treeToString(root)    {        // bases case        if (root == null)            return;         // push the root data as character        str += String.fromCharCode(root.data + '0'.charCodeAt());         // if leaf node, then return        if (root.left == null && root.right == null)            return;         // for left subtree        str += ('(');        treeToString(root.left);        str += (')');         // only if right child is present to        // avoid extra parenthesis        if (root.right != null)        {            str += ('(');            treeToString(root.right);            str += (')');        }    }         /* Let us construct below tree             1            / \            2 3            / \ \            4 5 6 */    let 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);    str = "";    treeToString(root);    document.write(str); </script>
Output:  
1(2(4)(5))(3()(6))
Time complexity: O(n) The preorder traversal is done over the n nodes. Space complexity: O(n). The depth of the recursion tree can go upto n in case of a skewed tree.  
YouTubeGeeksforGeeks500K subscribersBinary tree to string with brackets | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:59•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ymIgl_tFAwQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
29AjayKumar
princi singh
sanjeev2552
rameshtravel07
Strings
Tree
Strings
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python program to check if a string is palindrome or not
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Array of Strings in C++ (5 Different Ways to Create)
Caesar Cipher in Cryptography
Binary Tree | Set 1 (Introduction)
AVL Tree | Set 1 (Insertion)
Binary Tree | Set 3 (Types of Binary Tree)
Write a Program to Find the Maximum Depth or Height of a Tree
Binary Tree | Set 2 (Properties)