Python二叉树

标签 python class binary-tree

我实现了一个简单的树,但遇到了这个问题。当我尝试搜索一个节点并且它存在时,即使它在查找方法中的 if 语句处运行打印,它也会返回 None 。当我查找根节点时,它运行正常。所有其余节点均返回 None。有人能解释一下为什么吗?

class Node():
    def __init__(self,data):
        self.right = None
        self.left = None
        self.data = data

    def insert(self,data):
        if self.data == data:
            print "this item exists"
        elif self.data > data:
            if self.left == None:
                self.left = Node(data)
            else:
                self.left.insert(data)
        else:
           if self.right == None:
                self.right = Node(data)
           else:
                self.right.insert(data)

    def print_nodes(self):
        if self.left:
            self.left.print_nodes()
        print self.data
        if self.right:
            self.right.print_nodes()

    def lookup(self,data):
        if self.data == data:
            print 'exists'
            return 1
        elif self.data > data:
            if self.left != None:
                self.left.lookup(data)
            else:
                return -1
        elif self.data < data:
            if self.right != None:
                self.right.lookup(data)
            else:
                return -1


    def delete(self,data):
        if self.lookup(data)== -1:
            print "doesnot exists"
        else:
            if (not self.left) and (not self.right):
                self.data = None

root = Node(5)
#root.insert(3)
root.insert(3)
root.insert(2)
root.insert(6)
root.insert(61)
root.insert(62)
root.insert(63)

x = root.lookup(3)
print x

最佳答案

当根中不存在该项目时,您可以调用其子函数 lookup() 函数而不返回它们的值,因此即使代码在树中的某个位置找到了数据,您也会得到 None 值而不是结果 (1/-1)

替换此行:

self.left.lookup(data)
...
self.right.lookup(data)

用以下几行:

return self.left.lookup(data)
...
return self.right.lookup(data)

关于Python二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27343002/

相关文章:

python - Django : Send a mail to user when entry is created

python - Docker 要求无法安装

php - mysql_query() 期望参数 1 为字符串,使用类和函数时给出的资源

python - 如何为 Django/Mezzanine 站点的管理员设置权限

python - Python 中 except 语句的排序

Java-循环内返回数据准确性的问题

java - 获取实例的声明类: possible?

python - python中二叉树的最大深度

c++二叉树冲突类型错误

java - 字符串二分查找树