解法1:深度优先搜索算法,首先递归先序遍历树, 把结点加入路径。若该结点是叶子结点则比较当前路径和是否等于期待和。弹出结点,每一轮递归返回到父结点时,当前路径也应该回退一个结点!
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
# write code here
result = []
if root == None:
return result
self.num = expectNumber
self.DFS(root,result,[root.val])
return result
def DFS(self,root,result,path):
if root.left == None and root.right == None and sum(path) == self.num:
result.append(path)
if root.left:
self.DFS(root.left,result,path+[root.left.val])
if root.right:
self.DFS(root.right,result,path+[root.right.val])
return result
剑指Offer(二十四):二叉树中和为某一值的路径
最新推荐文章于 2022-05-13 11:04:59 发布