简体   繁体   中英

Insert function in a Binary Search Tree

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. Eg, 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM