Monday, May 15, 2006

Non-recursive tree traversals

Was asked recently by a friend to try this out. They are all almost the same except that postorder is a bit tricky. And do drop a gentle and kind comment if there are any mistakes :D

So here goes ...


Inorder:
--------
inorder(node *ptr)
{
lptr = ptr;
while(lptr!=NULL) {
stack.push(lptr);
lptr = lptr->left;
}

while(!stack.empty()) {
p = stack.pop();
print(p->data);

q = p->right;
while(q!=NULL) {
stack.push(q);
q = q->left;
}
}
}


Preorder:
---------
preorder(node *ptr)
{
lptr = ptr;
while(lptr!=NULL) {
print(lptr->data);
stack.push(lptr);
lptr = lptr->left;
}

while(!stack.empty()) {
p = stack.pop();
q = p->right;
while(q!=NULL) {
print(q->data);
stack.push(q);
q = q->left;
}
}
}


Postorder:
----------
postorder(node *ptr)
{
lptr = ptr;
while(lptr!=NULL) {
stack.push(lptr);
lptr = lptr->left;
}

while(!stack.empty()) {
p = stack.pop();

if(p->right==NULL || p->right==last) {
print(p->data);
}
else {
q = p->right;

// if right child exists, push back the parent node onto the stack
if(q!=NULL)
stack.push(p);

while(q!=NULL) {
stack.push(q);
q = q->left;
}
}
last = p;
}
}

No comments: