Java simple solution, 5 lines


  • 0
    H
        public static String tree2str(TreeNode t) {
        	if (t == null) { return ""; }
        	String strLeft = t.left == null ? t.right == null ? "" : "()" : "(" + tree2str(t.left) + ")" ;
        	String strRight = t.right == null? "" : "(" + tree2str(t.right) + ")";
        	String res = t.val 
        			+ strLeft
        			+ strRight;
        	return res;
        }
    

Log in to reply
 

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