-
Notifications
You must be signed in to change notification settings - Fork 0
/
b11.cpp
100 lines (90 loc) · 2.91 KB
/
b11.cpp
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
#include <iostream>
#include <string>
using namespace std;
//--------------------------------------------------------------------------------
struct Node {
string keyword;
string meaning;
Node* left;
Node* right;
Node(string key, string val) {
keyword = key;
meaning = val;
left = right = NULL;
}
};
//--------------------------------------------------------------------------------
Node* addNode(Node* node, string key, string val) {
if (node == NULL) {
node = new Node(key, val);
return node;
}
if (key < node->keyword) {
node->left = addNode(node->left, key, val);
}
else if (key > node->keyword) {
node->right = addNode(node->right, key, val);
}
else {
node->meaning = val;
}
return node;
}
//--------------------------------------------------------------------------------
Node* deleteNode(Node* node, string key) {
if (node == NULL) {
return node;
}
if (key < node->keyword) {
node->left = deleteNode(node->left, key);
}
else if (key > node->keyword) {
node->right = deleteNode(node->right, key);
}
else {
if (node->left == NULL) {
Node* temp = node->right;
delete node;
return temp;
}
else if (node->right == NULL) {
Node* temp = node->left;
delete node;
return temp;
}
}
return node;
}
//------------------------------------------------------------------------------------
void displayAsc(Node* node) {
if (node != NULL) {
displayAsc(node->left);
cout << "Keyword: " << node->keyword << ", Meaning: " << node->meaning << endl;
displayAsc(node->right);
}
}
//------------------------------------------------------------------------------------
void displayDesc(Node* node) {
if (node != NULL) {
displayDesc(node->right);
cout << "Keyword: " << node->keyword << ", Meaning: " << node->meaning << endl;
displayDesc(node->left);
}
}
//-------------------------------------------------------------------------------------
int main() {
Node* root = NULL;
root = addNode(root, "apple", "a fruit with red or green skin and a round shape");
root = addNode(root, "banana", "a long curved fruit which is yellow when ripe");
root = addNode(root, "carrot", "a long, thin, orange vegetable");
root = addNode(root, "date", "the sweet fruit of the date palm");
cout << "Ascending order:" << endl;
displayAsc(root);
cout << "\nDescending order:" << endl;
displayDesc(root);
root = deleteNode(root, "carrot");
cout << "\nAfter deleting carrot:" << endl;
displayAsc(root);
return 0;
}
//--------------------------------------------------------------------------------------