为什么它不终止?
var m_root : Node = root
private def insert(key: Int, value: Int): Node = {
if(m_root == null) {
m_root = Node(key, value, null, null)
}
var t : Node = m_root
var flag : Int = 1
while (t != null && flag == 1) {
if(key == t.key) {
t
}
else if(key < t.key) {
if(t.left == null) {
t.left = Node(key, value, null, null)
flag = 0
} else {
t = t.left
}
} else {
if(t.right == null) {
t.right = Node(key, value, null, null)
flag = 0
} else {
t = t.right
}
}
}
t
}
我编写了迭代版本,将节点插入二叉搜索树。我想在创建节点时终止,但它不会停止,因为我认为我没有分配终止条件。如何编辑代码以在插入节点时终止?
var m_root : Node = root
private def insert(key: Int, value: Int): Node = {
if(m_root == null) {
m_root = Node(key, value, null, null)
}
var t : Node = m_root
var flag : Int = 1
while (t != null && flag == 1) {
if(key == t.key) {
t
}
else if(key < t.key) {
if(t.left == null) {
t.left = Node(key, value, null, null)
flag = 0
} else {
t = t.left
}
} else {
if(t.right == null) {
t.right = Node(key, value, null, null)
flag = 0
} else {
t = t.right
}
}
}
t
}
I wrote iterative version insert a node to binary search tree. I want to terminate when node is created, but it doesn't stop, because I think I didn't assign terminating condition. How to I edit my code to terminate when a node inserted in?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定你到底想要什么行为,但原因很清楚。
您的循环是一个
while
条件,它将循环直到t
为null
。因此,当t
不为空时,循环将继续。您只将
t
分配给非空值 - 事实上,您专门检查 null 情况并通过创建新节点来阻止它发生。因此,您要么需要重新考虑循环条件,要么确保在某些情况下
t
实际上会变为 null,具体取决于您的实际算法要求。由于您在底部返回
t
,因此我建议 while 条件是错误的;唯一可能终止的方法是如果此时t
为 null,因此无论如何返回它都是没有意义的。I'm not sure exactly what behaviour you want, but the cause is quite clear.
Your loop is a
while
condition, which will loop untilt
isnull
. So whilet
is non-null the loop will continue.You only ever assign
t
to non-null values - in fact you're specifically checking for the null case and stopping it happening by creating a new node.So either you need to reconsider your loop condition, or ensure
t
does in fact become null in some cases, depending on what your actual algorithm requirements are.And since you're returning
t
at the bottom, I suggest the while condition is wrong; the only possible way this could terminate is ift
is null at this point, so it would be pointless to return this anyway.循环中“if”语句的第一个子句
...如果比较为真,则不执行任何操作。它不会终止循环。语句
t
与这里的return t
不是同义的。您可以在此时设置flag = 0
来终止循环。The first clause of your "if" statement in the loop
... does nothing if the comparison is true. It doesn't terminate the loop. The statement
t
is not synonymous withreturn t
here. You can setflag = 0
at that point to terminate the loop.