-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_tree.c
More file actions
93 lines (78 loc) · 1.82 KB
/
binary_tree.c
File metadata and controls
93 lines (78 loc) · 1.82 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
void add(struct Node** root, int data) {
// Create a new node
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
// Check if our tree is empty
if (*root == NULL) {
*root = newNode;
return;
}
// Traverse the tree
struct Node* curNode = *root;
struct Node* parent = NULL;
while (curNode != NULL) {
parent = curNode;
if (data < curNode->data) {
curNode = curNode->left;
} else {
curNode = curNode->right;
}
}
// We found a leaf node, lets the mount our new node
if (data < parent->data) {
parent->left = newNode;
} else {
parent->right = newNode;
}
}
int search(struct Node* root, int key) {
// If null, return false
if (root == NULL) {
return 0;
}
// Check the root
if (root->data == key) {
return 1;
}
// Search down appropriate subtree
if (key < root->data) {
return search(root->left, key);
} else {
return search(root->right, key);
}
}
void inorderTraversal(struct Node *root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
}
int main() {
struct Node* head = NULL;
add(&head, 4);
add(&head, 2);
add(&head, 1);
add(&head, 6);
add(&head, 7);
add(&head, 8);
inorderTraversal(head);
printf("\n");
printf("Search for 4\n");
int result = search(head, 4);
if (result == 1) {
printf("Found it!\n");
} else {
printf("Did not find it\n");
}
return 0;
}