-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchTree.c
More file actions
54 lines (47 loc) · 1.35 KB
/
Copy pathBinarySearchTree.c
File metadata and controls
54 lines (47 loc) · 1.35 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
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *left, *right;
};
// Function to create a new node
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->left = newNode->right = NULL;
return newNode;
}
// Function to insert a node
struct Node* insertNode(struct Node* root, int value) {
if (root == NULL) return createNode(value);
if (value < root->data) root->left = insertNode(root->left, value);
else if (value > root->data) root->right = insertNode(root->right, value);
return root;
}
// Inorder Traversal (Left, Root, Right)
void inorderTraversal(struct Node* root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
}
// Postorder Traversal (Left, Right, Root)
void postorderTraversal(struct Node* root) {
if (root != NULL) {
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->data);
}
}
int main() {
struct Node* root = NULL;
root = insertNode(root, 50);
insertNode(root, 30);
insertNode(root, 70);
printf("Inorder traversal: ");
inorderTraversal(root);
printf("\nPostorder traversal: ");
postorderTraversal(root);
return 0;
}