WAP to create a binary tree using Array and perform pre-order, in-order, and
post-order traversals.
#include <stdio.h>
#include <stdlib.h>
struct binary {
int data;
struct binary* left;
struct binary* right;
};
struct binary* newNode(int data)
{
struct binary* node = (struct binary*)malloc(sizeof(struct binary));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
void postorder(struct binary* node)
{
if (node == NULL)
return;
postorder(node->left);
postorder(node->right);
printf("%d ", node->data);
}
void inorder(struct binary* node)
{
if (node == NULL)
return;
inorder(node->left);
printf("%d ", node->data);
inorder(node->right);
}
void preorder(struct binary* node)
{
if (node == NULL)
return;
printf("%d ", node->data);
preorder(node->left);
preorder(node->right);
}
int main()
{
struct binary* node = newNode(1);
node->left = newNode(2);
node->right = newNode(3);
node->left->left = newNode(4);
node->left->right = newNode(5);
printf("\nPreorder display \n");
preorder(node);
printf("\nInorder display \n");
inorder(node);
printf("\nPostorder display \n");
postorder(node);
getchar();
return 0;
}
Comments
Leave a comment