Tree traversal
Tree traversal
different Types of Tree Traversals
ramthegreatcv- Posts : 55
Join date : 2009-01-30
Age : 36
Recursive: Simple and must know
- Code:
void inOrderRec(node* n){
if(n != NULL){
inOrderRec(n->lChild);
cout<<n->data;
inOrderRec(n->rChild);
}
}
void preOrderRec(node* n){
if(n != NULL){
cout<<n->data;
preOrderRec(n->lChild);
preOrderRec(n->rChild);
}
}
void postOrderRec(node* n){
if(n != NULL){
postOrderRec(n->lChild);
postOrderRec(n->rChild);
cout<<n->data;
}
}
ramthegreatcv- Posts : 55
Join date : 2009-01-30
Age : 36
Iterative Inorder
- Code:
void inOrderItr(node* n){
if(n == NULL)
return;
node* temp;
stack<node*> s;
while(true){
while(n){
s.push(n);
n = n->lChild;
}
if(! s.empty()){
n = s.top();
s.pop();
}
else
break;
cout<<n->data;
n = n->rChild;
}
return;
}
ramthegreatcv- Posts : 55
Join date : 2009-01-30
Age : 36
Iterative Post Order
- Code:
void postOrderItr(node* n){
/*
Suppose we push a NULL on the stack after a pointer to a node whose subtrees have both been explored.
When we pop the stack and find a NULL pointer, we'll know that the next pointer we pop represents a subtree that has been fully traversed;
it's value should be printed. Here's a possible implementation:
*/
stack<node *> s;
while ( n != NULL || !s.empty() )
{
for (; n != NULL; n = n->lChild )
s.push( n );
if ( s.top() != NULL )
{
n = s.top()->rChild;
s.push( NULL );
}
else
{
s.pop();
cout << s.top()->data;
s.pop();
n = NULL;
}
}
return;
}
Last edited by ramthegreatcv on Fri Jun 05, 2009 3:58 am; edited 1 time in total
ramthegreatcv- Posts : 55
Join date : 2009-01-30
Age : 36
Iterative Preorder
- Code:
void preOrderItr(node* n){
if(n == NULL)
return;
node* temp;
stack<node*> s;
s.push(n);
while(! s.empty() ){
temp = s.top();
s.pop();
cout<<temp->data;
if(temp->rChild != NULL)
s.push(temp->rChild);
if(temp->lChild != NULL)
s.push(temp->lChild);
}
return;
}
ramthegreatcv- Posts : 55
Join date : 2009-01-30
Age : 36
Similar topics
» left tree to right tree
» tree mirror code
» Code to check if a tree is a BST
» Binary tree to Linked List
» tree mirror code
» Code to check if a tree is a BST
» Binary tree to Linked List
Permissions in this forum:
You cannot reply to topics in this forum
|
|