C Program to Construct a Tree and Perform Tree Operations

This C Program constructs Tree & Perform Insertion, Deletion, Display.

Here is source code of the C Program to construct a Tree & Perform Insertion, Deletion, Display. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C Program to Construct a Tree & Perform Insertion, Deletion, Display 
  3.  */ 
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6.  
  7. struct btnode
  8. {
  9.     int value;
  10.     struct btnode *l;
  11.     struct btnode *r;
  12. }*root = NULL;
  13.  
  14. // Function Prototype
  15. void printout(struct btnode*);
  16. struct btnode* newnode(int);
  17.  
  18. void main()
  19. {
  20.     root=newnode(50);
  21.     root->l=newnode(20);
  22.     root->r=newnode(30);
  23.     root->l->l=newnode(70);
  24.     root->l->r=newnode(80);
  25.     root->l->r->r=newnode(60);
  26.     root->l->l->l=newnode(10);
  27.     root->l->l->r=newnode(40);
  28.     printf("tree elements are\n");
  29.     printf("\nDISPLAYED IN INORDER\n");
  30.     printout(root);
  31.     printf("\n");
  32. }
  33.  
  34. // Create a node
  35. struct btnode* newnode(int value)
  36. {
  37.     struct btnode* node = (struct btnode*)malloc(sizeof(struct btnode));
  38.     node->value = value;
  39.     node->l = NULL;
  40.     node->r = NULL;
  41.     return(node);
  42. }
  43.  
  44. // to display the tree in inorder
  45. void printout (struct btnode *tree)
  46. {
  47.     if (tree->l)
  48.         printout(tree->l);
  49.     printf("%d->", tree->value);
  50.     if (tree->r)
  51.         printout(tree->r);
  52. }

$ gcc tree1.c
$ a.out
tree elements are
 
DISPLAYED IN INORDER
10->70->40->20->80->60->50->30

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement
advertisement

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at programming examples on all topics, go to C Programming Examples.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.