-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbst.c
More file actions
112 lines (90 loc) · 2.13 KB
/
bst.c
File metadata and controls
112 lines (90 loc) · 2.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
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <stddef.h>
#include "queue.h"
struct node {
int data;
struct node* left;
struct node* right;
};
int getHeight2(struct node *root, int height) {
int leftHeight = height;
int rightHeight = height;
if (root->left != NULL) {
leftHeight = getHeight2(root->left, leftHeight + 1);
}
if (root->right != NULL) {
rightHeight = getHeight2(root->right, rightHeight + 1);
}
int foo = leftHeight > rightHeight ? leftHeight : rightHeight;
return foo;
}
int getHeight(struct node *root) {
int leftHeight = 0;
int rightHeight = 0;
if (root->left != NULL) {
leftHeight = getHeight2(root->left, leftHeight + 1);
}
if (root->right != NULL) {
rightHeight = getHeight2(root->right, rightHeight + 1);
}
return leftHeight > rightHeight ? leftHeight : rightHeight;
}
void printLOByQueue(struct queue * queue) {
struct node *node = NULL;
while (queue->begin != NULL && queue->end != NULL) {
node = (struct node *) dequeue(queue);
printf("%d ", node->data);
if (node->left != NULL) {
enqueue(queue, node->left);
}
if (node->right != NULL) {
enqueue(queue, node->right);
}
}
printf("LOT over");
}
void printLevelOrder(struct node *root) {
struct queue *queue = createQueue();
enqueue(queue, root->left);
enqueue(queue, root->right);
printf("LOT\n%d ", root->data);
printLOByQueue(queue);
//printf("\nLOT\n%d", ((struct node *)(queue->begin->data))->data);
}
void print(struct node *root) {
if (root != NULL) {
print(root->left);
printf("%d ", root->data);
print(root->right);
}
}
void insert (struct node **root, int data) {
if (*root == NULL) {
struct node *temp = malloc(sizeof(struct node));
temp->data = data;
temp->left = NULL;
temp->right = NULL;
*root = temp;
} else {
if (data < (*root)->data) {
insert(&((*root)->left), data);
} else {
insert(&((*root)->right), data);
}
}
}
void main() {
printf("BST\n");
struct node *root = NULL;
insert(&root, 5);
insert(&root, 6);
insert(&root, 7);
insert(&root, 4);
insert(&root, 1);
insert(&root, 9);
insert(&root, 2);
insert(&root, 12);
insert(&root, 3);
print(root);
printLevelOrder(root);
printf("Height %d", getHeight(root));
}