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
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.youkuaiyun.com/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。