Data Strucrures






Binary Tree Traversals


   Linear Search and Binary Search PPT

//Implement program for Binary Tree and Traversal using Recursive Procedure.
#include<stdio.h>
#include<stdlib.h>
struct btree
{
	int data;
	struct btree *lchild,*rchild;
};
typedef struct btree NODE;
NODE *create(NODE *);
NODE *getnode();
void inorder(NODE *);
void preorder(NODE *);
void postorder(NODE *);
int main()
{
	NODE *root;
	int choice;
	char ch;
	root=NULL;
	do
	{
		printf("\n\n\t\tMENU");
		printf("\n\t1.Insert Node");
		printf("\n\t2.Inorder");
		printf("\n\t3.Preorder");
		printf("\n\t4.Postorder");
		printf("\n\t0.Exit");
		printf("\nEnter your choice");
		scanf("%d",&choice);
		switch(choice)
		{
			case 1:
				root=create(root);
				break;
			case 2:
				printf("\nInorder Traversing Treen\n");
				inorder(root);
				break;
			case 3:
				printf("\nPreorder Traversing Tree\n\n");
				preorder(root);
				break;
			case 4:
				printf("\nPostorder Traversing Tree \n\n");
				postorder(root);
				break;
			case 0:
				exit(0);
				break;
			default:
				printf("\nWrong choice");
				break;
		}
		printf("\nDo you want to continue(y/n):");
		scanf("%s",&ch);
	}while(ch=='y'||ch=='Y');
	return(0);
}
NODE *getnode()
{
	NODE *temp;
	temp=(NODE *)malloc(sizeof(NODE));
	printf("\nEnter data: ");
	scanf("%d",&temp->data);
	temp->rchild=NULL;
	temp->lchild=NULL;
	return(temp);
}
NODE *create(NODE *root)
{
	NODE *temp,*ptr;
	char dir,ch;
	do
	{
		temp=getnode();
		if(root==NULL)
			root=temp;
		else
		{
			ptr=root;
			while(ptr!=NULL)
			{
				printf("\nThe current node is %d",ptr->data);
				printf("\nEnter direction L/R: ");
				scanf("%s",&dir);
				if(dir=='L'||dir=='l')
				{
					if(ptr->lchild!=NULL)
						ptr=ptr->lchild;
					else
					{
						ptr->lchild=temp;
						break;
					}
				}
				else if(dir=='R'||dir=='r')
				{
					if(ptr->rchild!=NULL)
						ptr=ptr->rchild;
					else
					{
						ptr->rchild=temp;
						break;
					}
				}
			}
		}
		printf("\nAdd more(y/n): ");
		scanf("%s",&ch);
	}while(ch=='y');
	return(root);
}
//Binary tree traversals Using Recursion
void inorder(NODE *ptr)
{
	if(ptr!=NULL)
	{
		inorder(ptr->lchild);
		printf("%d\t",ptr->data);
		inorder(ptr->rchild);
	}
}
void preorder(NODE *ptr)
{
	if(ptr!=NULL)
	{
		printf("%d\t",ptr->data);
		preorder(ptr->lchild);
		preorder(ptr->rchild);
	}
}
void postorder(NODE *ptr)
{
	if(ptr!=NULL)
	{
		postorder(ptr->lchild);
		postorder(ptr->rchild);
		printf("%d\t",ptr->data);
	}
}