129. Sum Root to Leaf Numbers

Medium
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.

太久沒有嘗過不看答案直接做出來的滋味了,這道題滿足了一下我。看了題之后很容易就聯(lián)想到了pathSum這一類跟root to leaf path相關(guān)的題,所以思路也比較清晰了,就是用DFS把所有路徑遍歷出來,最后來處理數(shù)字和加法就可以了。 這里依舊要注意一下,res.add(path)是不行的,因為path變空了之后res里面將什么也沒有, 必須要寫成res.add(new ArrayList<>(path)). 這樣不管path之后怎么變,我copy過來的path永遠(yuǎn)會保持現(xiàn)在的樣子,相當(dāng)于我只是把path里的元素copy過來了,并沒有copy path的reference。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int sumNumbers(TreeNode root) {
        int sum = 0;
        List<Integer> path = new ArrayList<>();
        List<List<Integer>> res = new ArrayList<>();
        if (root == null){
            return sum;
        }
        helper(root, path, res);
        for (List<Integer> list : res){
            int pathSum = 0;
            for (Integer i : list){
                pathSum *= 10;
                pathSum += i;
            }
            sum += pathSum;
        }
        return sum;
    }
    
    private void helper(TreeNode root, List<Integer> path, List<List<Integer>> res){
        if (root == null){
            return;
        }
        path.add(root.val);
        if (root.left == null && root.right == null){
            res.add(new ArrayList<>(path));
        }
        helper(root.left, path, res);
        helper(root.right, path, res);
        path.remove(path.size() - 1);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容