pub fn morris_traversal(root: Option<Rc<RefCell<TreeNode>>>) {
if root.is_none() {
return;
}
let mut current = root;
let mut most_right;
while let Some(current_node) = current.clone() {
println!("{}", current_node.borrow().value);
most_right = current_node.borrow().left.clone();
if most_right.is_some() {
while most_right.as_ref().unwrap().borrow().right.is_some()
&& most_right.as_ref().unwrap().borrow().right != current
{
most_right = most_right.unwrap().borrow().right.clone();
}
if most_right.as_ref().unwrap().borrow().right.is_none() {
most_right.unwrap().borrow_mut().right = current.clone();
current = current_node.borrow().left.clone();
continue;
} else {
most_right.unwrap().borrow_mut().right = None;
}
}
current = current_node.borrow().right.clone();
}
}
1
\
243
/
2
\
42
when it meets a bst like this ,it runs infinity.
"I'm stuck here, the loop isn't terminating. The condition for the loop is that most_right
should be the rightmost node of the current_node
's left subtree, which should be correct. However, even though the right
of the node with value 42
is already None
, the loop doesn't exit and continues to execute step-by-step. The values of current_node
and most_right
are different, but within the while
loop, they keep repeating, and they don't change. The loop doesn't exit."
need help! I'm thankful !