Just before I sat down to write code for morris inorder traversal I tried this example and am a bit confounded as to how its gonna work in this particular case:
80
/ \
60 100
\ /
70 90
/
65
/
63
\
64
Step 1:
60
\
70
/ \
65 80
/ \
63 100
\ /
64 90
As far as I understand the algorithm in the next step 70 will become the right child of 65, so what happens to 60? I am pretty sure I am missing something trivial but unfortunately unable to put my finger on it.
public void MorrisInorder() {
BSTNode<T> p = root, tmp;
while (p != null)
if (p.left == null) {
visit(p);
p = p.right;
}
else {
tmp = p.left;
while (tmp.right != null && // go to the rightmost node of
tmp.right != p) // the left subtree or
tmp = tmp.right; // to the temporary parent of p;
if (tmp.right == null) {// if 'true' rightmost node was
tmp.right = p; // reached, make it a temporary
p = p.left; // parent of the current root,
}
else { // else a temporary parent has been
visit(p); // found; visit node p and then cut
tmp.right = null; // the right pointer of the current
p = p.right; // parent, whereby it ceases to be
} // a parent;
}
}
Code I am following for morris inorder traversal.