1

I am teaching myself binary search tree and in this program i am inserting data in the tree but error 'NoneType' object has no attribute 'data' error is occuring.

from collections import deque
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def insert(rnode, data):
    if data > rnode.data:
        insert(rnode.right, data)
        rnode.right.data = data
        return print('Node inserted')
    if data < rnode.data:
        insert(rnode.left, data)
        rnode.left.data = data
        return print('Node inserted')

def bfs():
    q = deque()
    temp = self.root
    while temp:
        print(temp.data)
        q.append(temp.left)
        q.append(temp.right)
        temp = q.popleft()


root = Node(8)
insert(root, 3)
bfs()

ERROR:

Exception has occurred: AttributeError
'NoneType' object has no attribute 'data'
  File "/home/mayank/Documents/datastructures/binarysearchtree.py", line 9, in insert
    if data > rnode.data:
  File "/home/mayank/Documents/datastructures/binarysearchtree.py", line 14, in insert
    insert(rnode.left, data)
  File "/home/mayank/Documents/datastructures/binarysearchtree.py", line 29, in <module>
    insert(root, 3)

Help!!

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Mayank Pant
  • 145
  • 1
  • 8

1 Answers1

1

Your insert function assumes that rnode.right and rnode.left always refer to a tree into which a value can be inserted, but that's not the case if rnode is a leaf (which it will be, eventually, when inserting a new value) insert needs to create a new node for the new value.

def insert(rnode, data):
    if data > rnode.data:
        if rnode.right is None:
            rnode.right = Node(data)
        else:
            insert(rnode.right, data)
    if data < rnode.data:
        if rnode.left is None:
            rnode.left = Node(data)
        else:
            insert(rnode.left, data)
chepner
  • 497,756
  • 71
  • 530
  • 681