Construct String from Binary Tree

Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it.

Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship b…


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by SalahElhossiny

Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it.

Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree.


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public String tree2str(TreeNode t) {
        if(t==null)
            return "";
        if(t.left==null && t.right==null)
            return t.val+"";
        if(t.right==null)
            return t.val+"("+tree2str(t.left)+")";
        return t.val+"("+tree2str(t.left)+")("+tree2str(t.right)+")";   
    }
}



This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by SalahElhossiny


Print Share Comment Cite Upload Translate Updates
APA

SalahElhossiny | Sciencx (2022-09-07T04:05:48+00:00) Construct String from Binary Tree. Retrieved from https://www.scien.cx/2022/09/07/construct-string-from-binary-tree/

MLA
" » Construct String from Binary Tree." SalahElhossiny | Sciencx - Wednesday September 7, 2022, https://www.scien.cx/2022/09/07/construct-string-from-binary-tree/
HARVARD
SalahElhossiny | Sciencx Wednesday September 7, 2022 » Construct String from Binary Tree., viewed ,<https://www.scien.cx/2022/09/07/construct-string-from-binary-tree/>
VANCOUVER
SalahElhossiny | Sciencx - » Construct String from Binary Tree. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/09/07/construct-string-from-binary-tree/
CHICAGO
" » Construct String from Binary Tree." SalahElhossiny | Sciencx - Accessed . https://www.scien.cx/2022/09/07/construct-string-from-binary-tree/
IEEE
" » Construct String from Binary Tree." SalahElhossiny | Sciencx [Online]. Available: https://www.scien.cx/2022/09/07/construct-string-from-binary-tree/. [Accessed: ]
rf:citation
» Construct String from Binary Tree | SalahElhossiny | Sciencx | https://www.scien.cx/2022/09/07/construct-string-from-binary-tree/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.