LeetCode-Path Sum II
2016-11-23 10:50
295 查看
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and
return
Subscribe to see which companies asked this question
此题跟 Path Sum I 类似:http://blog.csdn.net/dancheren/article/details/53290645
对于II来说,由于需要找到所有符合条件的path,I只需要任意找到一条符合条件的path,就可结束查找。所以只需要在左或右子树中找到了一条path,就可以return
true将结果传递回去。则必须同时搜索左右子树。Path
Sum II要求返回所有路径的集合。这是很常见的一种函数返回类型要求。通常的做法是用一个一维vector变量存储当前解(path),用一个二维vector存储最终的解集合(allPaths)。每层递归不断更新当前解,直到递归结束找到解后更新解集合。Path
Sum II中要注意对path的reset。无论递归是否结束,或者解是否找到,都不能在返回前遗漏这一步reset。因为通过当前节点的所有path已经都访问到了,返回前需要从path中删除当前节点,以便重新构建其他path。
For example:
Given the below binary tree and
sum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
Subscribe to see which companies asked this question
此题跟 Path Sum I 类似:http://blog.csdn.net/dancheren/article/details/53290645
对于II来说,由于需要找到所有符合条件的path,I只需要任意找到一条符合条件的path,就可结束查找。所以只需要在左或右子树中找到了一条path,就可以return
true将结果传递回去。则必须同时搜索左右子树。Path
Sum II要求返回所有路径的集合。这是很常见的一种函数返回类型要求。通常的做法是用一个一维vector变量存储当前解(path),用一个二维vector存储最终的解集合(allPaths)。每层递归不断更新当前解,直到递归结束找到解后更新解集合。Path
Sum II中要注意对path的reset。无论递归是否结束,或者解是否找到,都不能在返回前遗漏这一步reset。因为通过当前节点的所有path已经都访问到了,返回前需要从path中删除当前节点,以便重新构建其他path。
相关文章推荐
- 【Leetcode】Path Sum II (Sum)
- leetcode: Path Sum II
- LeetCode | Path Sum II
- leetcode做题总结,动态规划I(Triangle,Unique PathsI/II,Minimum Path Sum,Climbing Stairs,Jump Game,Word Break)
- leetcode Path Sum II
- 【LeetCode】Path Sum II
- [LeetCode]Path Sum II
- functionclass[LeetCode]Path Sum II
- Leetcode | Path Sum I && II
- [Leetcode] Path Sum I,II,III
- LeetCode-Path Sum II
- LeetCode Path Sum II路径和II
- [leetcode] Path Sum II
- 【Leetcode】【python】Path Sum II
- [LeetCode] 070: Path Sum II
- [Leetcode]Path Sum && Path Sum II
- Leetcode146: Path Sum II
- [LeetCode] Unique Paths && Unique Paths II && Minimum Path Sum (动态规划之 Matrix DP )
- Leetcode-113. Path Sum II
- [leetcode]Path Sum II