Java recursive solution - easy and straightforward


  • 0
    C
    public String tree2str(TreeNode t) {
        if (t == null) {
            return "";
        }
        String res = String.valueOf(t.val);
        String left = tree2str(t.left);
        String right = tree2str(t.right);
        if (!right.equals("")) {
            res += "(" + left + ")" + "(" + right + ")";
        }
        else if (!left.equals("")) {
            res += "(" + left + ")";
        }
        return res;
    }
    

    Hope you like it!


Log in to reply
 

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