Construct String from Binary Tree


  • 0
    Y
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public String tree2str(TreeNode t) {
            if(t == null)
                return "";
            String s = new String();
            return helper(t);
        }
        
        private String helper(TreeNode root){
            String s = new String();
            s = s + "" + root.val;
            if(root.left == null && root.right == null){
                return s;}
             if(root.left == null)
                s = s+"()";
            else{
                s = s+"(" + helper(root.left);
                s = s + ")"; 
            }
            if(root.right != null){
                s = s + "(" + helper(root.right);
                s = s + ")";   
            }
            return s;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.