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:
Post a Comment