Python 中的路径和
假设我们有一颗树和一个和。我们必须找到一条路径,如果我们遵循这条路径,我们将得到一个和,且该和与给定的和匹配。假设树为 [0,-3,9,-10, null,5],且和为 14,则有一条路径 0 → 9 → 5
为了解决这个问题,我们将按照以下步骤进行操作。
如果根节点为 null,则返回 False
如果左右子树为空,则在 sum – root.val = 0 时返回 true,否则返回 false
返回 solve(root.left, sum – root.val) 或 solve(root.right, sum – root.val)
让我们看看以下实现以加深理解 −
示例
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.data = x self.left = None self.right = None def insert(temp,data): que = [] que.append(temp) while (len(que)): temp = que[0] que.pop(0) if (not temp.left): if data is not None: temp.left = TreeNode(data) else: temp.left = TreeNode(0) break else: que.append(temp.left) if (not temp.right): if data is not None: temp.right = TreeNode(data) else: temp.right = TreeNode(0) break else: que.append(temp.right) def make_tree(elements): Tree = TreeNode(elements[0]) for element in elements[1:]: insert(Tree, element) return Tree class Solution(object): def hasPathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: bool """ if not root : return False if not root.left and not root.right and root.data is not None: return sum - root.data == 0 if root.data is not None: return self.hasPathSum(root.left, sum-root.data) or self.hasPathSum(root.right, sum-root.data) tree1 = make_tree([0,-3,9,-10,None,5]) ob1 = Solution() print(ob1.hasPathSum(tree1, 14))
输入
tree1 = make_tree([0,-3,9,-10,None,5])
输出
True
广告