Share my Java Solution


  • 0
    A

    I found that there is already similar approach. I just share my solution here for anyone might be interested. The basic idea is to maintain a global variable to store the sum, and DFS on tree, whenever we come across a leaf node, add its value to the global sum. The code is as below:

    int total = 0;
    
    public int sumNumbers(TreeNode root) {
        if (root == null) return 0;
        sumNumbers(root, 0);
        return total;
    }
    
    private void sumNumbers(TreeNode node, int num) {
        num = num * 10 + node.val;
        if (node.left == null && node.right == null) {
            total += num;
            return;
        }
        if (node.left != null) sumNumbers(node.left, num);
        if (node.right != null) sumNumbers(node.right, num);
    }

Log in to reply
 

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