我正在尝试理解下面的递归函数,它表示一个特定的节点是否存在于二叉树中。我做了一些准备工作,得到了大部分递归部分,但最后一条返回语句( root.value、==、value或inleft或inright)让我感到困扰。
有没有人能帮我理解一下这个方法?
def existsInTree(self, root, value):
if root is None:
return False
else:
inleft = self.existsInTree(root.left, value)
inright = self.existsInTree(root.right, value)
print(inleft,inright)
return root.value == value or inleft or inright
example binary tree:
10
/ \
11 9发布于 2021-05-17 12:26:16
我们首先将根的数据与要搜索的节点的数据进行比较。如果找到匹配项,则将该标志设置为true。否则,在左子树中搜索节点,然后在右子树中搜索节点。
发布于 2021-05-17 12:27:23
还有另一种查看返回语句的方法,您可以在or关键字处拆分返回语句
def ifRootExists(self,root, value):
if (root == None):
return False
if (root.value == value):
return True
""" then recur on left sutree """
res1 = ifrootExists(root.left, value)
# root found, no need to look further
if res1:
return True
""" root is not found in left,
so recur on right subtree """
res2 = ifrootExists(root.right, value)
return res2发布于 2021-05-17 12:43:39
我们可以从上面的函数中得到某个节点是否存在的结果。
算法如下。
总而言之,inleft和inright表示V是否包含在子树中。
https://stackoverflow.com/questions/67563967
复制相似问题