二叉搜索树期间的属性错误?

Attribute error during binary search tree?

我正在尝试编写软件来打印包含预定字符串的 BST,这是我目前拥有的代码。由于某种原因,它会打印前两个字符串,然后它会崩溃并给我一个 "AttributeError: 'NoneType' object has no attribute 'value'" 错误

class Node(object):
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None
        self.count = 1

def insert(root, value):
    if not root:
        return Node(value)
    elif root.value == value:
        root.count += 1
    elif value < root.value:
        root.left = insert(root.left, value)
    else:
        root.right = insert(root.right, value)
    return root

def create(seq):
    root = None
    for word in seq:
        root = insert(root, word)
    return root

def preOrder(root):
    print(root.value)
    print("root.value printed")
    if root.left != 0:
        preOrder(root.left)
    if root.right != 0:
        preOrder(root.right)


src = ['foo', 'bar', 'foobar', 'barfoo', 'overflow', 'python']
tree = create(src)
print(preOrder(tree))

这是它将给我的输出:

foo
root.value printed
bar
root.value printed
Traceback (most recent call last):
File "", line 37, in <module>
print(preOrder(tree))
File "", line 29, in preOrder 
preOrder(root.left)
File "", line 29, in preOrder 
preOrder(root.left)
File "", line 26, in preOrder 
print(root.value)
AttributeError: 'NoneType' object has no attribute 'value'

我无法确定为什么会这样?我知道这个错误意味着它指向不存在的东西,但我不知道为什么。

我想你只需要改变你的preOrder方法,当rootNone时停止:

def preOrder(root):
    if root is None:
        return
    print(root.value)
    print("root.value printed")
    if root.left != 0:
        preOrder(root.left)
    if root.right != 0:
        preOrder(root.right)

此外,您不需要 print(preOrder(tree)),您可以只做 preOrder(tree),因为它所做的只是打印树。否则你会得到一个额外的 None 打印,这是一个没有 return 任何东西的方法的默认 return。

你问题中的缩进是错误的,但我认为这是偶然的。