【问题标题】:Python BST search - TypeErrorPython BST 搜索 - TypeError
【发布时间】:2023-04-04 11:24:01
【问题描述】:

我有以下二叉搜索树节点类:

class Node: 
    # Implement a node of the binary search tree.
    # Constructor for a node with key and a given parent
    # parent can be None for a root node.
    def __init__(self, key, parent = None): 
        self.key = key
        self.parent = parent 
        self.left = None # We will set left and right child to None
        self.right = None
        # Make sure that the parent's left/right pointer
        # will point to the newly created node.
        if parent != None:
            if key < parent.key:
                assert(parent.left == None), 'parent already has a left child -- unable to create node'
                parent.left = self
            else: 
                assert key > parent.key, 'key is same as parent.key. We do not allow duplicate keys in a BST since it breaks some of the algorithms.'
                assert(parent.right == None ), 'parent already has a right child -- unable to create node'
                parent.right = self

我正在尝试搜索树以查看给定键是否存在。这是我的搜索功能:

    def search(self, key):
        print("self.key: ", type(self.key), "\n", "key: ", type(key))    
        if self.key == key: 
            return (True, self)
        # your code here
        elif self.key < key:
            if self.right == None:
                return (False, self)
            else: self.search(self.right)
        elif self.key > key:
            if self.left == None:
                return (False, self)
            else: self.search(self.left)

但是,我尝试更改 elif 并不断收到错误消息。当我输入以下行时,我得到了相关的错误:

elif self.key &lt; key: : TypeError: '

elif self.key() &lt; key: : TypeError: 'int' object is not callable

elif key(self) &lt; key: : TypeError: 'int' object is not callable

我做错了什么?

【问题讨论】:

  • 看来您传递给searchkey 参数是Node 对象而不是整数。你如何调用函数? print 语句的输出是什么?
  • (b, found_node) = t1.search(18) assert b and found_node.key == 18, 'test 8 failed'
  • 我刚刚注意到,您没有返回递归调用的值:else: self.search(self.right) 应该是 else: return self.search(self.right) 与 left 相同。
  • 谢谢,好收获!但是,我仍然收到 elif 子句的错误消息。
  • 另外,您正在对self 进行递归调用,但它应该是leftright。并且您需要传递搜索键:else: return self.right.search(key)

标签:
python
class
typeerror
nodes