[] 24. Offer to prove safety and python implemented as a binary tree path a certain value

Title Description

  • An input and a binary value, request from the root to the leaf node, and the value equal to the path
  • Deformation depth-first search
    Here Insert Picture Description

Problem-solving ideas


Deformation depth-first search

Two solutions python


Recursive


# -*- 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]]

Backtracking


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
Published 99 original articles · won praise 6 · views 3979

Guess you like

Origin blog.csdn.net/weixin_42247922/article/details/103991390