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
|
#include <iostream>
using namespace std;
struct elem {
char key;
elem* left, * right;
} *root = NULL;
void add(int n, elem*& t);
void obb(elem* t);
void print(int n, int h);
void show(elem* t, int h);
int height(elem* t);
elem* search(int k, elem* t);
elem* search_iter(elem* t, int k);
void main()
{
int num, ch, h, k;
do {
cout << "Menu\n";
cout << "1.Add element\n";
cout << "2.Preorder\n";
cout << "3. Search and show\n";
cout << "4.Show\n";
cout << "Exit\n";
cout << "Your choice: ";
cin >> ch;
switch (ch)
{
case 1:
cout << "num="; cin >> num;
add(num, root); cout << endl;
break;
case 2: obb(root);
h = height(root);
show(root, h);
cout << endl;
break;
case 3:
cout << "Cin element, whose descendants you're looking for\n";
cin >> k;
if (k != p->key) cout << "Wrong number";
else elem *&p = search_iter(k); show(root, height(root));
break;
case 4: h = height(root);
show(root, h);
cout << "\n"; break;
}
} while (ch != 0);
system("pause");
}
void add(int n, elem*& t) {
if (t == NULL) {
t = new elem;
t->key = n;
t->left = t->right = NULL;
}
else
{
if (t->key < n)
add(n, t->right);
else
add(n, t->left);
}
}
void obb(elem* t) {
if (t) {
cout << t->key << " ";
obb(t->left);
obb(t->right);
}
}
void print(int n, int h) {
for (int i = 0; i < h; i++)
cout << "\t";
cout << n << "\n";
}
void show(elem* t, int h) {
if (t) {
show(t->right, h + 1);
print(t->key, h);
show(t->left, h + 1);
}
}
int height(elem* t) {
int u, v;
if (!t) return -1;
u = height(t->left);
v = height(t->right);
if (u > v) return u + 1;
else return v + 1;
}
elem* search(int k, elem* t)
{
if (t)
{
while (t->key != k);
{
if (t->key < k)
t = t->right;
else
t = t->left;
}
}
return t;
}
elem* search_iter(elem* t, int k)
{
while (t && t->key != k)
if (t->key < k)
t = t->right;
else
t = t->left;
return t;
}
|