信管117118李志荣数据结构实验四---树和二叉树的实验

本文介绍了一个使用顺序存储方式实现的二叉树数据结构。通过定义结构体存储节点信息,并使用数组进行存储,实现了节点的设置、遍历等功能。此外,还提供了一个简单的交互式菜单供用户操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//head.h
#include<string>
const int Maxsize = 32;
struct information 
{
	int value;
	int exist;
};
class Sequential_Storage_Tree
{
public:
	Sequential_Storage_Tree() { memset(tree, 0, sizeof(information)*Maxsize); count = 0; }
	void Set();
	void Sequence();
	void Print();	
	void Codyledon();
private:
	information tree[Maxsize];
	int count;
};

#include"head.h"
#include<iostream>
using namespace std;
void Sequential_Storage_Tree::Set()
{
	if (count > Maxsize) throw  "overflow";
	cout << "enter a data and a location : ";
	int data,location;
	cin >> data>>location;
	if (location > Maxsize) throw "wrong location";
	if (tree[location].exist != 0) throw "you will coveer the origin";
	else {
		tree[location].value = data;
		count++;
		tree[location].exist = 1;
	}
}

void Sequential_Storage_Tree::Sequence()
{for(int i=1;i<=Maxsize;i++)
{
	if (tree[i].exist != 0) cout << "the data in " << i<< " is " << tree[i].value<<endl;
}
}

void Sequential_Storage_Tree::Print()
{
	for (int i = 1; i<=Maxsize; i++)
	{
		if (tree[i].exist != 0) 
		{ cout << "the data in " << i << " is " << tree[i].value << endl;
		if (i > 1 && tree[i / 2].exist != 0) cout << "the parent are" << i / 2<<endl;
		if (2 * i <= count&&tree[2 * i].exist != 0) cout << "the left child are" << 2*i<<endl;
		if (2 * i + 1<= count&&tree[2 * i + 1].exist != 0) cout << "the right child are" << 2 * i+1<<endl;
		}
	}
}

void Sequential_Storage_Tree::Codyledon()
{
	cout << "the Codyledon have :";
	int tally = 0;
	
	for (int i = 1; i <= Maxsize; i++)
	{
		if (tree[i].exist != 0) tally++;		
		if (tree[i].exist!=0&&tree[2 * i].exist == 0 && tree[2 * i + 1].exist == 0) cout << i<<"     ";
		if (tally >= count) break;
	}
}

#include<iostream>
#include"head.h"

int main()
{
	Sequential_Storage_Tree binary;
	std::cout << "MENU";
	int use = 0;
	while (use != 5)
	{
		std::cout << "\n1.SET\n2.Sequence\n3.Print\n4.Codyledon\n5.Exit\nNow input a number to use function:";
		std::cin >> use;
		switch (use)
		{
		case 1:binary.Set(); break;
		case 2:binary.Sequence(); break;
		case 3:binary.Print(); break;
		case 4:binary.Codyledon(); break;		
		default:
			break;
		}
	}
	return 0;
}
算法空间储存效率:1/2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值