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);
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容