My insert method in my Binary search tree is creating problems. I'm getting separate nodes instead of one. What have I done incorrectly?
class Node:
def __init__(this,key,value):
this.key = key
this.value = value
this.left = null
this.right = null
def insert(this,root,key,value):
if(root == null):
root = Node(key,value)
return root
elif(root.key < key):
root.left = root.insert(root.left,key,value)
return root
elif(root.key > key):
root.right = root.insert(root.right,key,value)
return root
else:
print("Data already exists!")
return root
Your code does a strange modification along the search path. E.g., look at the line
It says "the new left child of the node is what's returned by
root.insert
".So let's say it continues down 30 more levels, and then it finds the key. It executes
So that updates all sorts of things up. Probably not what you want.
You can solve this issue by changing
to