【剑指Offer】 24.二叉树中和为某一值的路径 python实现

题目描述

  • 输入一棵二叉树和一个值,求从根结点到叶结点的和等于该值的路径
  • 深度优先搜索变形
    在这里插入图片描述

解题思路


深度优先搜索的变形

python两种解法


递归实现


# -*- 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
        ret = []
        if not root:
            return ret
        path = [root]
        sums = [root.val]

        def dfs(root):
            if root.left:
                path.append(root.left)
                sums.append(sums[-1]+root.left.val)
                dfs(root.left)
            if root.right:
                path.append(root.right)
                sums.append(sums[-1] + root.right.val)
                dfs(root.right)
            if not root.left and not root.right:
                if sums[-1] == expectNumber:
                    ret.append([p.val for p in path])
            path.pop()
            sums.pop()

        dfs(root)
        return ret

if __name__ == '__main__':
    t = Tree()
    t.construct_tree([1, 3, 6, 4, 3, 1, 1])
    print(find_path(t.root, 8))  # [[1, 3, 4], [1, 6, 1], [1, 6, 1]]

回溯算法


class Solution:
    def FindPath(self, root, expectNumber):
        def subFindPath(root):
            if root:
                b.append(root.val)
                if not root.right and not root.left and sum(b) == expectNumber:
                    a.append(b[:])
                else:
                    subFindPath(root.left),subFindPath(root.right)
                b.pop()
        a, b = [], []
        subFindPath(root)
        return a
发布了99 篇原创文章 · 获赞 6 · 访问量 3979

猜你喜欢

转载自blog.csdn.net/weixin_42247922/article/details/103991390