facebook like button

21 January, 2014

program that prints inorder traversal of tree and count the leaf nodes.

#include<stdio.h>
struct x{
int data;
struct x *right;
struct x *left;
};
typedef struct x node;
node* createTree(node * ,int );
node* createNode(int x);
void inorder(node** );
int countLeaf(node** );
int main()
{
int i,x,j,n;
node *root=NULL;
printf("how many nodes you want to create\n");
scanf("%d",&n);
if(n>0)
{
printf("enter the data for nodes\n");
for(i=0;i<n;i++)
{
scanf("%d",&x);
root=createTree(root,x);
}
}
inorder(&root);
j=countLeaf(&root);
printf("\nthe leaf nodes are %d\n",j);
return 0;

}
node* createNode(int x)
{
node* a;
a=(node*)malloc(sizeof(node));
a->data=x;
a->right=NULL;
a->left=NULL;
return a;
}
node* createTree(node* root,int x)
{
if(root==NULL)
{
root=createNode(x);
return root;
}
else if(root->data<x)
root->right=createTree(root->right,x);
else
root->left=createTree(root->left,x);
return root;
}
void inorder(node **root)
{
if(*root==NULL)
return;
else{
inorder(&((*root)->left));
printf("%d->",(*root)->data);
inorder(&((*root)->right));
}
}
int countLeaf(node **root)
{
static int count=0;
if(*root==NULL)
return count;
  else if((*root)->left==NULL && (*root)->right==NULL)
{
count++;
return count;
}
else{
countLeaf(&((*root)->left));
countLeaf(&((*root)->right));
}
}

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply