-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathBinaryTree.cpp
More file actions
57 lines (49 loc) · 1.13 KB
/
BinaryTree.cpp
File metadata and controls
57 lines (49 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data_element;
struct node *left, *right;
};
struct node *new_node(int data_element)
{
struct node *temp = (struct node *)malloc(sizeof(struct node)); // Allocating memory to the node
temp->data_element = data_element;
temp->left = temp->right = NULL;
return temp;
}
void display(struct node *root) // A function for the inroder traversal of the binary tree
{
if (root != NULL)
{
display(root->left);
printf("%d \n", root->data_element);
display(root->right);
}
}
struct node* insert(struct node* node, int data_element) // Function to insert a new node
{
if (node == NULL) return new_node(data_element); // Return a new node if the tree if empty
if (data_element < node->data_element)
{
node->left = insert(node->left, data_element);
}
else if (data_element > node->data_element)
{
node->right = insert(node->right, data_element);
}
return node;
}
int main()
{
struct node *root = NULL;
root = insert(root, 10);
insert(root, 10);
insert(root, 50);
insert(root, 60);
insert(root, 90);
insert(root, 100);
insert(root, 150);
display(root); // Function to display the binary tree elements
return 0;
}