Binary Tree Source Code (Data Structures)

 #include<stdio.h> ]

#include<conio.h>
#include<stdlib.h>
void inorder_traversal();
void preorder_traversal();
void postorder_traversal();
struct node
{
	int item;
	struct node *left,*right;
};
struct node * createnode(int);
struct node * insert_left(struct node*,int);
struct node * insert_right(struct node*,int);
void main()
{
  struct node *root = createnode(10);
  insert_left(root,20);
  insert_right(root,30);
  insert_left(root->left,40);

  printf("\n Inorder Traversal");
  inorder_traversal(root);
  printf("\nPreorder Traversal");
  preorder_traversal(root);
  printf("\nPostorder Traversal");
  postorder_traversal(root);
  getch();
}
//node creation
struct node* createnode(int value)
{
	struct node *new_node=(struct node*)malloc(sizeof(struct node));
	new_node->item=value;
	new_node->left=NULL;
	new_node->right=NULL;
	return new_node;
}

//insert left
struct node *insert_left(struct node *root,int value)
{
	root->left=createnode(value);
	return root->left;
}

//insert right
struct node *insert_right(struct node *root,int value)
{
	root->right=createnode(value);
	return root->right;
}

void inorder_traversal(struct node *root)
{
	if(root==NULL)
	return;
	inorder_traversal(root->left);
	printf("%d",root->item);
	inorder_traversal(root->right);
}

void preorder_traversal(struct node *root)
{
	if(root==NULL)
	return;
	printf("%d",root->item);
	preorder_traversal(root->left);
	preorder_traversal(root->right);
}

void postorder_traversal(struct node *root)
{
	if(root==NULL)
	return;
	postorder_traversal(root->left);
	postorder_traversal(root->right);
	printf("%d",root->item);
}

Previous Post Next Post