129. Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

For example,

    1
   / \
  2   3
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.

Solution1:

思路:Recursive[递归post-order dfs来upwards累积],并上面的sum 调用时downwards向下传递
Time Complexity: O(N) Space Complexity: O(N) 递归缓存

Solution2:

思路: 全局g_sum, dfs更新

Solution1 Code:

class Solution {
    public int sumNumbers(TreeNode root) {
        return dfsSum(root, 0);
    }
    
    private int dfsSum(TreeNode node, int cur_sum) {
        if(node == null) return 0;
        if(node.left == null && node.right == null) return cur_sum * 10 + node.val;
        int sum = dfsSum(node.left, cur_sum * 10 + node.val) + dfsSum(node.right, cur_sum * 10 + node.val);
        return sum;
    }
}

Solution2 Code:

class Solution {
    
    private int g_sum = 0;
    
    public int sumNumbers(TreeNode root) {
        dfsSum(root, 0);
        return g_sum;
    }
    
    private void dfsSum(TreeNode node, int cur_sum) {
        if(node == null) return;
        if(node.left == null && node.right == null) {
            g_sum += (cur_sum * 10 + node.val);
        }
        dfsSum(node.left, cur_sum * 10 + node.val);
        dfsSum(node.right, cur_sum * 10 + node.val);
    }
}

你可能感兴趣的:(129. Sum Root to Leaf Numbers)