python - Insert function in a Binary Search Tree -


my insert method in binary search tree creating problems. i'm getting separate nodes instead of one. have 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 exists!")         return root 

your code strange modification along search path. e.g., @ line

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

it says "the new left child of node what's returned root.insert".

so let's continues down 30 more levels, , finds key. executes

else:     print("data exists!")     return root 

so updates sorts of things up. not want.


you can solve issue changing

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

to

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

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -