SCHOOL OF CODE BUILDERS
Learn To CODE. Become A DEVELOPER.
Pages
HOME
DATA STRUCTURES
STRINGS
ARRAYS
MATRIX
BINARY TREES
LINKED LIST
STACK
QUEUE
SORTING
SEARCHING
C
PYTHON
PSEUDOCODE
CONTEST PROBLEMS
ALGORITHMS
PATTERNS
PHP
C PUZZLES
C INTERVIEW QUESTIONS
JAVA
C++
HASHING
RECURSION
BASIC C PROGRAMS
TCS-CODEVITA
FACEBOOK
CONTACT US
C program to build a binary tree
C program to build a binary tree
Output:
4 2 5 1 6 3 7
Implementation:
/* Source: http://www.coderegister.co.in/2015/04/create-binary-tree-do-inorder-traversal.html */ #include
#include
/* Create a structure block, such that each node holds a. data b. pointer to left child c. pointer to right child */ struct node { int data; struct node *left, *right; }; /* Insert function a. Creates a memory block (new node) b. Assigns input data to new node's data c. Initialize the left child & right child of the new node to NULL */ struct node* insert ( int data ) { /* Creating a memory block "temp" to hold the new data */ struct node *temp = ( struct node* ) malloc ( sizeof ( struct node ) ); /* Assigning the data to the new node */ temp -> data = data; /* Initializing the new node's left & right child as NULL */ temp -> left = temp -> right = NULL; return temp; } /* Inorder Traversal to display the node's of the tree in the order a. Left node b. Root node c. Right node */ void inorder ( struct node *root ) { if ( root == NULL ) return; /* Recur for Left subtree */ inorder ( root -> left ); /* Print the Root node -> data */ printf ( "%d ",root -> data ); /* Recur for Right subtree */ inorder ( root -> right ); } int main() { /* Create a root pointer & initialize it to NULL */ struct node *root = NULL; /* Insert the nodes where you want it to be */ root = insert ( 1 ); root -> left = insert ( 2 ); root -> right = insert ( 3 ); root -> left -> left = insert ( 4 ); root -> left -> right = insert ( 5 ); root -> right -> left = insert ( 6 ); root -> right -> right = insert ( 7 ); /* Inorder Function to do Inorder traversal in the tree */ inorder(root); return 0; }
PREVIOUS
NEXT
HOME