数据结构与算法16、剑指Offer10-二叉树中和为某一值的路径(深度优先遍历)

在这里插入图片描述
这题可以分解为两个步骤,第一个步骤是深度优先遍历DFS,找到所有的路径,第二个步骤就是每次符合条件的路径都放到结果中,最后sort一下即可,这题也体现出Python的易用性。

在实现代码前,有一个非常重要的Python特性需要解释一下,就是深拷贝和浅拷贝,比如res.append(path)这条语句里,res和path是两个列表
将path列表append到res列表中时,在那一刻的确是path的数据都在res中,但是后续如果path的数据改变了,那么res列表中的数据就会随着path数据的改变而改变,这叫做
浅拷贝

为了解决这个问题,我们使用深拷贝,即语句可以改为
res.append(path[:])

接下来的代码就很容易了,直接上代码,对于边界问题,自己画个样例,判断一下即可。

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回二维列表,内部每个列表表示找到的路径
    def FindPath(self, root, expectNumber):
        # write code here
        res = []
        path = []
        if root is None:
            return res
        
        def DFS(proot):
            path.append(proot.val)
            if proot.left is None and proot.right is None:
                if sum(path) == expectNumber:  # Python的好处
                    res.append(path[:])
            if proot.left is not None:
                left = DFS(proot.left)
            if proot.right is not None:
                right = DFS(proot.right)
            path.pop()
        DFS(root)
        res.sort()  # Python的好处
        return res 
发布了71 篇原创文章 · 获赞 20 · 访问量 4835

猜你喜欢

转载自blog.csdn.net/qq_22795223/article/details/105475650