Java Recursive solution


  • 0
    A
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        StringBuilder sb = new StringBuilder();
        boolean root = true;
        public String tree2str(TreeNode t) {
           if (t == null) return "";
            if(root == true) {
                sb.append(t.val);
                root = false;
            }
            else sb.append("("+ t.val);
            if(t.left!=null) tree2str(t.left);
            if(t.left == null && t.right!=null) sb.append("()");
            if(t.right!=null) tree2str(t.right);
            sb.append(")");
            return sb.substring(0,sb.length()-1).toString();
        }
    }
    
    
    
    
    
    
    
    
    
    
    

Log in to reply
 

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