Accepted Java 5 line solution


  • 1
    V
    public int sumNumbers(TreeNode root) {
        if (root == null) return 0;
        return sumNumbersTree(root, "0");
    }
    
    private int sumNumbersTree(TreeNode root, String s) {
        if (root.left == null && root.right == null) return Integer.valueOf(s + root.val);
        return (root.left != null ? sumNumbersTree(root.left, s + root.val) : 0) + (root.right != null ? sumNumbersTree(root.right, s + root.val) : 0);
    }

Log in to reply
 

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