[英]Insert function in a Binary Search Tree
My insert method in my Binary search tree is creating problems. 我的Binary搜索树中的insert方法正在创建问题。 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
". 它说:“该节点的新左子节点是root.insert
返回的root.insert
”。
So let's say it continues down 30 more levels, and then it finds the key. 因此,假设它继续下降了30个级别,然后找到了关键。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.