-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertion of element
43 lines (43 loc) · 1.12 KB
/
Insertion of element
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
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct Node* insertNode(struct Node* root, int data) {
if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insertNode(root->left, data);
}
else if (data > root->data) {
root->right = insertNode(root->right, data);
}
return root;
}
void inorderTraversal(struct Node* root) {
if (root == NULL) return;
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
int main() {
struct Node* root = NULL;
int elements[] = {50, 30, 70, 20, 40, 60, 80};
int n = sizeof(elements) / sizeof(elements[0]);
for (int i = 0; i < n; i++) {
root = insertNode(root, elements[i]);
}
printf("In-order Traversal (Sorted Order):\n");
inorderTraversal(root);
return 0;
}