繁体   English   中英

试图了解 python 中的二叉树(递归函数)中存在的节点

[英]trying to understand node exists in binary tree (recursion func) in python

我试图理解下面的递归 function 表示特定节点是否存在于二叉树中。 我做了功课,得到了大部分递归部分,但最后一个返回语句(return 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

我们将首先将根的数据与要搜索的节点的数据进行比较。 如果找到匹配项,则将该标志设置为 true。 否则,在左子树中搜索节点,然后在右子树中搜索。

还有另一种查看 return 语句的方法,您可以在or关键字处拆分 return 语句

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

我们可以从上面的 function 中得到某个节点是否存在的结果。

算法如下。

  1. root 是 None 或 Not。 如果没有,取回父 function 调用的 position,其值为“False”。
  2. 否则,function会根据当前节点不断搜索。
  • inleft 是 function "existsInTree" 的值,其中当前节点的左子节点是根节点。
  • inright 是 function "existsInTree" 的值,其中当前节点的右孩子是根节点。
  1. 假设我们要搜索名为 V 的值。 V 存在于树中意味着当前值是 V 或在左树中,或在右树中。

总而言之,inleft 和 inright 表示 V 是否包含在子树中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM