Search code examples
pythonsearchbinary-search-treepreorder

Attribute error during binary search tree?


I'm trying to write software to print a BST containing strings in preorder, and this is the code I have so far. for some reason it will print the first two strings and then it will crach and give me a "AttributeError: 'NoneType' object has no attribute 'value'" error

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))

This is the output it will give me:

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'

I can't pin down why this is happening? I know this error means it's pointing at something that doesn't exists, but I don't know why.


Solution

  • I think all you need is to change your preOrder method to stop when root is None:

    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)
    

    Also, you don't need print(preOrder(tree)), you can just do preOrder(tree), since all it does is print the tree. Otherwise you will get an extra None printed, which is the default return of a method that does not return anything.

    Your indentation in your question is wrong, but I assume that is accidental.