Java Simple Solution


  • 0
    S
    public class Solution {
        public String tree2str(TreeNode t) {
            if (t == null) 
                return "";
            
            String left = tree2str(t.left);
            String right = tree2str(t.right);
            
            if (right.length() > 0)
                return t.val + "(" + left + ")(" + right + ")"; 
            else if (left.length() > 0)
                return t.val + "(" + left + ")"; 
            else
                return t.val + "";
        }
    }
    

Log in to reply
 

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