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?
I’m not sure exactly what behaviour you want, but the cause is quite clear.
Your loop is a
whilecondition, which will loop untiltisnull. So whiletis non-null the loop will continue.You only ever assign
tto 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
tdoes in fact become null in some cases, depending on what your actual algorithm requirements are.And since you’re returning
tat the bottom, I suggest the while condition is wrong; the only possible way this could terminate is iftis null at this point, so it would be pointless to return this anyway.