Java Solution that works for any numbers not just 0-9


  • -1
    E
    public int sumNumbers(TreeNode root) {
        return sumNumbersHelper(root,"");
    }
    
    private int sumNumbersHelper(TreeNode treeNode, String number) {
        if(treeNode==null) {
            if(number != "") {
                return Integer.parseInt(number);
            }
            return 0;
        }
        int right = 0;
        int left = 0;
        if (treeNode.left!=null && treeNode.right!=null) {
            left = sumNumbersHelper(treeNode.left, number + treeNode.val);
            right = sumNumbersHelper(treeNode.right, number + treeNode.val);
        } else if (treeNode.left!=null) {
            left = sumNumbersHelper(treeNode.left, number + treeNode.val);
        } else if (treeNode.right!=null) {
            right = sumNumbersHelper(treeNode.right, number + treeNode.val);
        } else {
            return Integer.parseInt(number + treeNode.val);
        }
        return left + right;
    }

Log in to reply
 

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