This function takes a link to a trees as an argument and calls function visit with each of the nodes in the tree as arguments.
Recursive tree traversal
void traverse(link h, void visit(link)){
if(h==0) return;
visit(h);
traverse(h->l,visit);
traverse(h->r,visit);
}
There can be three order in which we can traverse a node :
Three traversals depicted in order
Preorder Stack Call(leftmost)
Doing inorder traversal is same as solving Towers of Hanoi.
Note doing the postorder traversal is equivalent to evaluating postfix expressions.
Non recursive implementation
void traverse(link h, void visit(link)){
stack<link> s(max);
s.push(h);
while(!s.empty()){
visit(h=s.pop());
if(h->r !=0) s.push(h->r); // TO ensure we don't push empty links
if(h->l !=0) s.push(h->l);
}
}
preoder
, push the right subtree , then left and then nodeinorder
, push the right subtree, then node and then left subtree.postorder
, push the node, then the right subtree, and then left subtree.Picture of stack at different times
This strategy is based on reading top to down and left to right.
Remarkably, we can achieve it just by changing one word in the last program.
exchanging stack
by queue
does it
because we process nodes in the order they appear.