leetcode 113. 路径总和 II
2019-03-12 21:03
302 查看
-
题目链接 https://leetcode-cn.com/problems/path-sum-ii/submissions/
-
题目描述
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
-
给定如下二叉树,以及目标和
sum = 22
,5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
返回:
[ [5,4,11,2], [5,8,4,5] ]
解题思路
- DFS or BFS
代码
- python (BFS)
[code]class Solution: def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]: if not root: return [] from queue import deque q = deque([[root, root.val, [root.val]]]) res = [] while q: cur = q.popleft() if not cur[0].left and not cur[0].right and cur[1] == sum: res.append(cur[2]) continue if cur[0].left: q.append([cur[0].left, cur[1] + cur[0].left.val, cur[2] + [cur[0].left.val]]) if cur[0].right: q.append([cur[0].right, cur[1] + cur[0].right.val, cur[2] + [cur[0].right.val]]) return res
[code]class Solution: def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]: if not root:return [] ans = [] def _dfs(root, sum, res): nonlocal ans if not root.left and not root.right and sum - root.val == 0: return ans.append(res + [root.val]) if root.left: _dfs(root.left, sum - root.val, res + [root.val]) if root.right: _dfs(root.right, sum - root.val , res + [root.val]) _dfs(root, sum, []) return ans
相关文章推荐
- LeetCode 113. 路径总和 II Python
- Leetcode 113. 路径总和 II
- LeetCode-113.路径总和II(相关话题:深度优先)
- leetcode 113. Path Sum II (路径和) 解题思路和方法
- leetcode 113. Path Sum II (路径和) 解题思路和方法
- [LeetCode] 113. Path Sum II 路径和 II
- leetcode 113. Path Sum II-路径和|回溯算法
- leetcode-路径总和II(python)
- 利用python 完成leetcode 113 路径总和 II
- [LeetCode]113. Path Sum II(列出二叉树根到叶路径和等于sum的所有路径)
- LeetCode 113. Path Sum II(路径和)
- 【LeetCode】#113路径总和II(Path Sum II)
- Leetcode 113. Path Sum II 路径和2 解题报告
- LeetCode 113. Path Sum II
- [LeetCode] 113. Path Sum II
- leetcode113. Path Sum II
- 【LeetCode】113. Path Sum II
- LeetCode *** 113. Path Sum II
- [leetcode]113. Path Sum II (medium)
- [LeetCode]112. Path Sum&113. Path Sum II