Binary tree implementation with inorder traversal in C
Binary tree has a root node with two child nodes. Child nodes are named as left child and right child. Let us create a binary tree in c.
C implementation:
- This implementation starts from the including the built-in header files.
- First, a node structure is created using structure. It has the member variables as data,left and right nodes.
- ‘create_Node()’ is used to create node. It allocates the memory for new node. The data and its position is assigned.
- ‘insert()’- This function is used to add the nodes to binary node. It includes the data.
- ‘in_order()’ -It is a type of traversal to print the data in order.
- ‘main()’- It helps to get the value from the user and call the functions. Finally, it prints the output value.
Code:
#include <stdio.h>
#include <stdlib.h>
// Create a node
structure
int b_data;
struct b_Node
*c_left, *c_right;
};
// let us implement a Function create_Node()
struct b_Node* create_Node(int value) {
struct b_Node*
newNode = (struct b_Node*)malloc(sizeof(struct b_Node));
newNode->b_data
= value;
newNode->c_left
= newNode->c_right = NULL;
return newNode;
}
// implement insert() function
struct b_Node* insert(struct b_Node* root, int value) {
if (root == NULL)
{
return
create_Node(value);
}
if (value <
root->b_data) {
root->c_left = insert(root->c_left, value);
} else {
root->c_right = insert(root->c_right, value);
}
return root;
}
// create the function Inorder traversal
void in_order(struct b_Node* root) {
if (root != NULL)
{
in_order(root->c_left);
printf("%d ", root->b_data);
in_order(root->c_right);
}
}
int main() {
struct b_Node*
b_root = NULL;
// binary tree
creation and inserting the values
b_root =
insert(b_root, 80);
insert(b_root,
25);
insert(b_root,
96);
insert(b_root,
15);
insert(b_root,
43);
insert(b_root,
50);
insert(b_root,
100);
printf("Inorder Traversal: ");
in_order(b_root);
return 0;
}
Output:
Here is the output.
Inorder Traversal: 15 25 43 50 80 96 100
Hope, you understood the concept and program. Keep Coding!!!
Comments
Post a Comment