试题描述:“遍历算法应用”的算法在计算机上调通(加上主函数)
程序的初始二叉树:
#include <bits/stdc++.h>
using namespace std;
int count = 0;
typedef struct node *Tree;
struct node {
int element;
Tree left;
Tree right;
int Height;
};
int getHeight(Tree T) {
if (T) return T->Height;
return -1;
}
Tree insertTree(Tree T, int element) {
if (!T) {
T = (Tree)malloc(sizeof(struct node));
T->element = element;
T->left = NULL;
T->right = NULL;
} else {
if (T->element < element) T->right = insertTree(T->right, element);
else if (T->element >= element) T->left = insertTree(T->left, element);
}
T->Height = max(getHeight(T->left), getHeight(T->right)) + 1;
return T;
}
void PreOrder(Tree T) {
if (!T) return;
cout << T->element << " ";
PreOrder(T->left);
PreOrder(T->right);
}
void MidOrder(Tree T) {
if (!T) return;
MidOrder(T->left);
cout << T->element << " ";
MidOrder(T->right);
}
void ReaOrder(Tree T) {
if (!T) return;
ReaOrder(T->left);
ReaOrder(T->right);
cout << T->element << " ";
}
int CountLeaves(Tree T) {
if (T->left == NULL && T->right == NULL) return 1;
if (T->left == NULL) return CountLeaves(T->right);
if (T->right == NULL) return CountLeaves(T->left);
return CountLeaves(T->left) + CountLeaves(T->right);
}
void FindAllLeaves(Tree T) {
if (!T) return;
if (T->left == NULL && T->right == NULL) cout << T->element << " ";
FindAllLeaves(T->left);
FindAllLeaves(T->right);
}
int main(int argc, char const *argv[]) {
Tree T = NULL;
int a[7] = {5, 3, 4, 2, 6, 7, 8}, element;
for (int i = 0; i < 7; ++i)
T = insertTree(T, a[i]);
char c = 'a', t, num;
while (c != 'n') {
system("cls");
cout << "输入对应字母完成操作:" << endl;
cout << "\ti:插入节点" << endl;
cout << "\tp:先序遍历二叉树" << endl;
cout << "\tm:中序遍历二叉树" << endl;
cout << "\tl:后序遍历二叉树" << endl;
cout << "\tg:获取全部叶节点" << endl;
cout << "\tn:获取叶节点个数" << endl;
cout << "\th:返回当前节点的高度" << endl;
cin >> t;
switch (t) {
case 'i':
cout << "请输入需要插入的数字:";
cin >> element;
T = insertTree(T, element);
cout << "数字" << element << "已成功插入!" << endl;
break;
case 'p':
cout << "先序遍历结果:";
PreOrder(T);
cout << endl;
break;
case 'm':
cout << "中序遍历结果:";
MidOrder(T);
cout << endl;
break;
case 'l':
cout << "后序遍历结果:";
ReaOrder(T);
cout << endl;
break;
case 'n':
num = CountLeaves(T);
cout << "节点个数为: ";
printf("%d\n", num); //很奇怪cout会输出方块
break;
case 'g':
cout << "输出所有叶节点: ";
FindAllLeaves(T);
cout << endl;
break;
case 'h':
cout << "当前二叉树高度为:" << getHeight(T) << endl;
break;
default:
system("cls");
cout << "无该操作!!!" << endl;
}
cout << endl << "返回或退出(任意键/n): ";
cin >> c;
}
return 0;
}