Java 4 lines solution - Easy to Understand


  • 0
    S
    public class Solution {
        public String tree2str(TreeNode t) {
            if (t == null) return "";
            if (t.left == null && t.right == null) return String.valueOf(t.val);
            if (t.right == null) return t.val + "(" + tree2str(t.left) + ")"; //only missing right node need to be handled separately, missing left node need to keep empty ()
            return t.val + "(" + tree2str(t.left) + ")" + "(" + tree2str(t.right) + ")";
        }
    }
    

Log in to reply
 

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