Java Solution: 14lines. Divide & Conquer. Easy to Understand


  • 0
    L

    For most of problems about BinaryTree, we can use divide & conquer to solve it.
    So, to this problem, we can do like follows:

    public class Solution {
        public String tree2str(TreeNode t) {
            if (t == null) return "";
            String left = tree2str(t.left);
            String right = tree2str(t.right);
            if (right.equals("")) {
                if (left.equals("")) return Integer.toString(t.val);
                else return Integer.toString(t.val) + "(" + left + ")";
            } 
            return Integer.toString(t.val) + "(" + left + ")" + "(" + right + ")";
        }
    }
    

Log in to reply
 

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