recent

Inorder Tree Traversal

Inorder Traversal:

   1. Traverse the left subtree, i.e., call Inorder(left-subtree)
   2. Visit the root.
   3. Traverse the right subtree, i.e., call Inorder(right-subtree)
Example: Inorder traversal for program is 4 2 5 1 3.


#include<stdio.h>
#include<stdlib.h>

struct node{

 int data;
 struct node *left;
 struct node *right;
};

//create new node when function CreateNode Called

struct node *CreateNode(int data)   //function to create new node & returning a node so return type is struct
{

struct node *new_node=(struct node*)malloc(sizeof(struct node));  //Allocate memory to new node

new_node->data=data;

new_node->left=NULL;
new_node->right=NULL;

return new_node;
}

void InorderTraversal(struct node *root)
{
if(root==NULL)
return;

InorderTraversal(root->left);
printf("%d\t",root->data);
InorderTraversal(root->right);

}

main()
{

struct node *root;
root=CreateNode(1);

root->left=CreateNode(2);
root->right=CreateNode(3);

root->left->left=CreateNode(4);
root->right->right=CreateNode(5);

printf("\nInorde traversal is :\t");
InorderTraversal(root);

}
Powered by Blogger.