You are on page 1of 14

TREE TRAVESALS

BINARY TREE TRAVESALS TECHNIQUE

• A tree traversal is a method of visiting very node in the tree. By visit,


we mean that some type of operation is performed example you may
wish to print the contents of the nodes
FOUR WAYS TO TRAVERSE A BINARY
TREE

• Preorder
• In order
• Post order
• Level order
In the first three traversals methods, the left subtree of a node is
traversed before the right subtree. The difference among them comes
form the difference in the time at which a root node is visited.
RECURSIVE TRAVERSAL ALGORITHMS
INORDER TRAVERSAL
In case of in order traversal the root of each subtree is visited after its
left subtree has been traversed but before the traversal of its right
subtree begins. The steps for traversing a binary tree in in order
traversals are:
• Visit the left subtree, using in order
• Visit the root
• Visit the right subtree, using in order
ALGORITHM FOR INORDER
TRAVERSAL
void inorder(node *root)
{
if(root != NULL) {
inorder(root->lchild);
print root -> data;
inorder(root->rchild);
}
}
PREORDER TRAVESAL
In a preorder traversal , each root node is visited before its left and
right subtrees are traversed.
Preorder search is also called backtracking
The steps for traversing a binary tree in preorder traversals are:
• Visit the root
• Visit the left subtree, using preorder
• Visit the right subtree, using preorder
ALGORITHM FOR PREORDER
TRAVESALS
void preorder(node *root)
{
if( root != NULL )
{
print root -> data;
preorder (root -> lchild);
preorder (root -> rchild);
}
}
POST ORDER TRAVESAL
• In a post traversal , each root is visited after its left and right subtrees
have been traversed.
• The steps for traversing a binary tree in post order traversal are:
• Visit the left subtree, using post order
• Visit the right subtree using post order
• Visit root
The algorithm for postorder
void postorder(node *root)
{
if( root != NULL )
{
postorder (root -> lchild);
postorder (root -> rchild);
print (root -> data);
}
}
LEVEL ORDER TRAVSESAL
• In a level order traversal , the nodes are visited level by level starting
from the root , and going from left to right.
• The level order traversal requires a queue data structure. It is not
possible to develop a recursive procedure to traverse the binary tree
in level order .
• This is nothing but a breath first search technique
Algorithm for level order traversal
void levelorder()
{ int j;
for(j = 0;
j < ctr; j++)
{
if(tree[j] != NULL)
print tree[j] -> data;
}
}

You might also like