Insert function in a Binary Search Tree

444 Views Asked by At

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
1

There are 1 best solutions below

4
On

Your code does a strange modification along the search path. E.g., look at the line

 root.left = root.insert(root.left,key,value)

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

else:
    print("Data already exists!")
    return root

So that updates all sorts of things up. Probably not what you want.


You can solve this issue by changing

root.left = root.insert(root.left,key,value)

to

return root.insert(root.left,key,value)