-
Notifications
You must be signed in to change notification settings - Fork 0
/
in order
53 lines (53 loc) · 1.44 KB
/
in order
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
#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) {
root = createNode(data);
} else {
char direction;
printf("Insert %d to the left or right of %d? (l/r): ", data, root->data);
scanf(" %c", &direction);
if (direction == 'l') {
root->left = insertNode(root->left, data);
} else if (direction == 'r') {
root->right = insertNode(root->right, data);
} else {
printf("Invalid direction! Use 'l' for left and 'r' for right.\n");
}
}
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 n, data;
printf("Enter the number of nodes: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("Enter data for node %d: ", i + 1);
scanf("%d", &data);
root = insertNode(root, data);
}
printf("In-order traversal of the binary tree: ");
inorderTraversal(root);
return 0;
}