剑指 Offer 34. 二叉树中和为某一值的路径

94 阅读1分钟

在这里插入图片描述
思路:DFS,采用前序遍历,构建一个列表path[]来存叶子节点的路径,
如果遍历到叶子节点,该路径不满足target,那么删除path中最后一个元素,同时返回上一层的父节点继续遍历
如果该path满足target,将path的拷贝加入到result中

class Solution:
    def pathSum(self, root: TreeNode, target: int) -> List[List[int]]:
        res=[]
        path=[]
        def DFS(root,target):
        	#遇到叶子节点停止遍历,采用前序遍历
            if not root:return
            #将root节点添加至路径,并更新target,判断该路径是否满足条件
            path.append(root.val)
            target-=root.val
            if not root.left and not root.right and target==0:
                res.append(path[:])
            #前序遍历
            DFS(root.left,target)
            DFS(root.right,target)
            #遍历至叶子节点时,若路径不符合条件,删掉path中最后一个叶子节点,返回上一层
            path.pop()
        DFS(root,target)
        return res