实验4:二叉树的基本操作

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;
}
posted @   这题太难了  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示