首页 > 其他 > 详细

[LeetCode] 113. 路径总和 II

时间:2019-06-29 19:39:32      阅读:81      评论:0      收藏:0      [点我收藏+]

题目链接 : https://leetcode-cn.com/problems/path-sum-ii/

题目描述:

给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

说明: 叶子节点是指没有子节点的节点。

示例:

给定如下二叉树,以及目标和 sum = 22,

          5
         /         4   8
       /   /       11  13  4
     /  \    /     7    2  5   1

返回:

[
   [5,4,11,2],
   [5,8,4,5]
]

思路:

和上一题一样, 用DFS只不过在遍历时候,要记录val而已

def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
        res = []
        if not root: return []
        def helper(root,sum, tmp):
            if not root:
                return 
            if not root.left and not root.right and sum - root.val == 0 :
                tmp += [root.val]
                res.append(tmp)
                return 
            helper(root.left, sum - root.val, tmp + [root.val])
            helper(root.right, sum - root.val, tmp + [root.val])
        helper(root, sum, [])
        return res

java

class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList<>();
        helper(root, sum, res, new ArrayList<Integer>());
        return res;
    }

    private void helper(TreeNode root, int sum, List<List<Integer>> res, ArrayList<Integer> tmp) {
        if (root == null) return;
        tmp.add(root.val);
        if (root.left == null && root.right == null && sum - root.val == 0) res.add(new ArrayList<>(tmp));
        helper(root.left, sum - root.val, res, tmp);
        helper(root.right, sum - root.val, res, tmp);
        tmp.remove(tmp.size() - 1);
    }
}

相关题型 : 112. 路径总和

[LeetCode] 113. 路径总和 II

原文:https://www.cnblogs.com/powercai/p/11107476.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!