Easy to understand recursive solution


  • 0
    X
    public String tree2str(TreeNode t) {
            if (t == null) 
            	return "";
            
            if (t.left == null && t.right == null) {
            	return String.valueOf(t.val);
            }
            
            StringBuilder sb = new StringBuilder();
            sb.append(t.val);
            sb.append("(").append(tree2str(t.left)).append(")");
            if (t.right != null) {
            	sb.append("(").append(tree2str(t.right)).append(")");
            }
            
            return sb.toString();
        }
    

Log in to reply
 

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