Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python在二叉树中搜索节点_Python_Python 3.x_Class_Binary Tree - Fatal编程技术网

python在二叉树中搜索节点

python在二叉树中搜索节点,python,python-3.x,class,binary-tree,Python,Python 3.x,Class,Binary Tree,我在二叉树中搜索有困难, 我想检查根目录是否存在,但遇到错误。 我做错了什么 这是我的完整代码: class Node: def __init__(self, data): self.left = None self.right = None self.data = data def printTree(self): if self.left: self.left.PrintTree()

我在二叉树中搜索有困难, 我想检查根目录是否存在,但遇到错误。 我做错了什么

这是我的完整代码:

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

    def printTree(self):
        if self.left:
            self.left.PrintTree()
        print(self.data),
        if self.right:
            self.right.PrintTree()

    def insert(self, data):
        """ Compare the new value with the parent node """
        if self.data:
            if data < self.data:
                if self.left is None:
                    self.left = Node(data)
                else:
                    self.left.insert(data)
            elif data > self.data:
                if self.right is None:
                    self.right = Node(data)
                else:
                    self.right.insert(data)
        else:
            self.data = data

    def is_exist(self, val):
        if val < self.data:
            if self.left is None:
                return None, None
            return self.left.exists(val, self)
        elif val > self.data:
            if self.right is None:
                return None, None
            return self.right.exists(val, self)
        else:
            return self.data
我得到的厄洛尔:

    return self.left.exists(val, self)
AttributeError: 'Node' object has no attribute 'exists'

您用错误的名称调用函数。此外,如果调用对象的方法,则不会指定
self
。看见您编写了
return self.right.exists(val,self)
,但您应该编写
return self.right.is_exist(val)

self.left.exists
不在您的代码中。你的意思是
self.left.is_exist()
?很抱歉,我的所有测试都改变了它。。。但是还是不行。对不起,我错过了你的第二道题。我编辑了我的答案。
    return self.left.exists(val, self)
AttributeError: 'Node' object has no attribute 'exists'