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.

太久没有尝过不看答案直接做出来的滋味了,这道题满足了一下我。看了题之后很容易就联想到了pathSum这一类跟root to leaf path相关的题,所以思路也比较清晰了,就是用DFS把所有路径遍历出来,最后来处理数字和加法就可以了。 这里依旧要注意一下,res.add(path)是不行的,因为path变空了之后res里面将什么也没有, 必须要写成res.add(new ArrayList<>(path)). 这样不管path之后怎么变,我copy过来的path永远会保持现在的样子,相当于我只是把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);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容