将BST节点与str问题进行比较

时间:2018-11-16 19:49:00

标签: python string binary-search-tree nodes typeerror

这是我用来尝试查找包含单词的BST中保存的特定值的搜索功能。但是,当我运行它时,在行elif root < root.value:

上出现错误
def search(root, target):
    print("Target is: " + target + "\n")
    if root.value == target or root == None:
        print("Found target: " + target)
        return root
    elif root < root.value:
        return search(root.left, target)
        print("Searching left")
    else:
        return search(root.right, target)
        print("Searching right")

它说TypeError: '<' not supported between instances of 'Node' and 'str',据我所知,我也可以使用<>比较常规字符串,但是我似乎无法用它来比较包含以下内容的根节点一个字符串和另一个包含字符串的节点?他们是我应该进行比较的另一种方式吗?

1 个答案:

答案 0 :(得分:0)

您正在尝试将rootroot.value进行比较。

我认为您的意思是这样的:

def search(root, target):
    print("Target is: " + target + "\n")
    if root.value == target or root is None: # changed to is, 
                                             # though you may want a 4th case for this
        print("Found target: " + target)
        return root
    elif target < root.value: #Notice I changed this to target instead of root
        print("Searching left")
        return search(root.left, target)
    else:
        print("Searching right")
        return search(root.right, target)