c++解释: new相当于malloc()函数,其他没有区别!
点击查看代码
#include<iostream>
using namespace std;
struct tree {
int data;
tree* light, *ture;
};
int jie, shen,maxx;
//创建
tree* chu() {
tree* head;
head = new tree;
cout << "请输入数值:\n";
cin >> head->data;
if (head->data == 0)
return nullptr;
jie++;
cout << "请输入该"<<head->data<<"的左结点,无则输入 0 \n";
head->light = chu();
cout << "请输入该" << head->data << "的右结点,无则输入 0 \n";
head->ture = chu();
return head;
}
//前序
void printqian(tree* head) {
if (head == nullptr) return;
cout << head->data << ' ';
printqian(head->light);
printqian(head->ture);
}
//中序
void printzong(tree* head) {
if (head == nullptr) return;
printzong(head->light);
cout << head->data << ' ';
printzong(head->ture);
}
//后序
void printhou(tree* head) {
if (head == nullptr) return;
printhou(head->light);
printhou(head->ture);
cout << head->data << ' ';
}
void sheng(tree* head) {
if (head == nullptr) return;
shen++;
maxx = max(maxx, shen);
sheng(head->light);
sheng(head->ture);
shen--;
}
int mumo() {
cout << "您可以进行一下操作:\n";
cout << "1:建立新二叉树\n";
cout << "2:前序输出二叉树\n";
cout << "3:中序输出二叉树\n";
cout << "4:后序输出二叉树\n";
cout << "5:查看现二叉树节点树\n";
cout << "6:查看深度\n";
cout << "其他:退出\n";
int k; cin >> k;
return k;
}
int main() {
tree* head=nullptr;
while (true) {
int k = mumo();
if (k < 1 && k>6) break;
switch (k) {
case 1:
head = chu();
cout << "建立完成!\n";
break;
case 2:
cout << "前序输出为:";
printqian(head);
cout << endl;
break;
case 3:
cout << "中序输出为:";
printzong(head);
cout << endl;
break;
case 4:
cout << "后序输出为:";
printhou(head);
cout << endl;
break;
case 5:
cout <<"二叉树的节点有" << jie <<"个" << endl;
break;
case 6:
maxx = -1;
sheng(head);
cout <<"该二叉树深度为:" << maxx << endl;
break;
}
}
return 0;
}