-
Notifications
You must be signed in to change notification settings - Fork 0
/
cTree.h
146 lines (125 loc) · 2.94 KB
/
cTree.h
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
enum Ptr {
Left,
Right
};
typedef struct TreeNode {
double val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
void InitializeTreeNode(TreeNode* treeNode) {
treeNode->left = NULL;
treeNode->right = NULL;
}
TreeNode* Getmin(TreeNode* root) {
TreeNode* cur = root;
while (cur && cur->left) {
cur = cur->left;
}
return cur;
}
TreeNode* CreateTreeNode(double key) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
if (node != NULL) {
InitializeTreeNode(node);
node->val = key;
}
return node;
}
TreeNode* Find(TreeNode* root, double key) {
if (root == NULL || root->val == key) {
return root;
}
if (root->val > key) {
return Find(root->left, key);
}
else {
return Find(root->right, key);
}
}
bool Contains(TreeNode* root, double key) {
return Find(root, key) != NULL;
}
TreeNode* Insert(TreeNode* root, double key) {
if (Contains(root, key)) {
return root;
}
if (root == NULL) {
return CreateTreeNode(key);
}
if (root->val > key) {
root->left = Insert(root->left, key);
}
else if (root->val < key) {
root->right = Insert(root->right, key);
}
return root;
}
TreeNode* Remove(TreeNode* root, double key) {
if (root == NULL) {
return root;
}
if (root->val > key) {
root->left = Remove(root->left, key);
}
else if (root->val < key) {
root->right = Remove(root->right, key);
}
else {
if (!root->right) {
TreeNode* temp = root->left;
free(root);
return temp;
}
else if (!root->left) {
TreeNode* temp = root->right;
free(root);
return temp;
}
else {
root->val = Getmin(root->right)->val;
root->right = Remove(root->right, root->val);
}
}
return root;
}
void FreeTree(TreeNode* root) {
if (root == NULL) {
return;
}
FreeTree(root->left);
FreeTree(root->right);
free(root);
}
void PrintPtr(TreeNode* root, enum Ptr ptr) {
if (ptr == Right) {
if (root->right)
printf("%.2lf rightPointer -> %.2lf \n", root->val, root->right->val);
else
printf("No right pointer\n");
}
else if (ptr == Left) {
if (root->left)
printf("%.2lf <- %.2lf leftpointer", root->left->val, root->val);
else {
printf("No left pointer\n");
}
}
}
TreeNode* FindParent(TreeNode* root, double key) {
if (root == NULL ||
(root->left != NULL && root->left->val == key) ||
(root->right != NULL && root->right->val == key)) {
return root;
}
if (root->val > key) {
return FindParent(root->left, key);
}
else {
return FindParent(root->right, key);
}
}