C Program to Construct a Tree with insertion operation and display the output

Rumman Ansari   2017-10-14   Student   Data structure > Tree   1593 Share

This C Program constructs Tree & Perform Insertion, Display.

The C program is successfully compiled and run on a windows system. The program output is also shown below.

Program

/*
 * C Program to Construct a Tree & Perform Insertion, Deletion, Display 
 */ 
#include 
#include 
 
struct btnode
{
    int value;
    struct btnode *left;
    struct btnode *right;
}*root = NULL;
 
// Function Prototype
void printout(struct btnode*);
struct btnode* newnode(int);
 
void main()
{
    root=newnode(51);
    root->left=newnode(21);
    root->right=newnode(31);
    root->left->left=newnode(71);
    root->left->right=newnode(82);
    root->left->right->right=newnode(62);
    root->left->left->left=newnode(11);
    root->left->left->right=newnode(42);
    printf("tree elements are\n");
    printf("\nDISPLAYED IN INORDER\n");
    printout(root);
    printf("\n");
}
 
// Create a node
struct btnode* newnode(int value)
{
    struct btnode* node = (struct btnode*)malloc(sizeof(struct btnode));
    node->value = value;
    node->left = NULL;
    node->right = NULL;
    return(node);
}
 
// to display the tree in inorder
void printout (struct btnode *tree)
{
    if (tree->left)
        printout(tree->left);
    printf("%d->", tree->value);
    if (tree->right)
        printout(tree->right);
}

Output

tree elements are

DISPLAYED IN INORDER
11->71->42->21->82->62->51->31->
Press any key to continue . . .