I'm using an example from a free book Open Data Structures (in Java) by Pat Morin. I believe i understand the concept of what is going on for tree traversal (keep going left until you can't go any more left, then right and then back up.
I'm a little flummoxed on the code below however. How exactly does it know to change branches in a structure such as:
r(oot)
|
- -
| |
a b
| |
c d
void traverse2() {
Node u = r, prev = nil, next;
while (u != nil) {
if (prev == u.parent) {
if (u.left != nil) next = u.left;
else if (u.right != nil) next = u.right;
else next = u.parent;
} else if (prev == u.left) {
if (u.right != nil) next = u.right;
else next = u.parent;
} else {
next = u.parent;
}
prev = u;
u = next;
} }
from what I can see it automatically goes to parent even though the root has none?