完全二叉树数组法

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

#define MAXSIZE 100
#define OK 1
#define ERROR 0

typedef int Status;
typedef int TElemType;

//定义结构体
typedef struct
{
	TElemType data[MAXSIZE];
	int size;
}CompleteBinaryTree;

//初始化
Status InitTree(CompleteBinaryTree& T)
{
	T.size = 0;
	return OK;
}

//检查二叉树是否满了
Status IsFull(CompleteBinaryTree& T)
{
	if (T.size = MAXSIZE)
		return ERROR;
}

//输入二叉树的值
Status CreatTree(CompleteBinaryTree& T)
{
	int much = 0;
	int value = 0;
	printf("how much values\n");
	scanf("%d", &much);
	for (int i = 0; i < much; i++)
	{
		scanf("%d", &value);
		T.data[T.size] = value;
		T.size++;
	}
	return OK;
}

//获取节点的值
Status GetNode(CompleteBinaryTree& T,int n, TElemType& e)
{
	if (n > T.size)
	{
		printf("input error\n");
		return ERROR;
	}
	e = T.data[n-1];
	return e;
}

//获取该点左孩子的值
Status GetLeftChild(CompleteBinaryTree& T, int n, TElemType& e)
{
	if (n > T.size)
	{
		printf("input error\n");
		return ERROR;
	}
	e = T.data[2 * (n - 1)];
	return e;
}

//获取该点右孩子的值
Status GetRightChild(CompleteBinaryTree& T, int n, TElemType& e)
{
	if (n > T.size)
	{
		printf("input error\n");
		return ERROR;
	}
	e = T.data[2 * (n - 1) + 1];
	return e;
}

//获取父节点的值
Status GetParent(CompleteBinaryTree& T, int n, TElemType& e)
{
	if (n > T.size)
	{
		printf("input error\n");
		return ERROR;
	}
	if (n / 2 == 0)
	{
		e = T.data[n / 2];
	}
	else
	{
		e = T.data[(n - 1) / 2];
	}
	return e;
}

//遍历完全二叉树
Status Print(CompleteBinaryTree& T)
{
	for (int i = 0; i < T.size; i++)
	{
		printf("%d ", T.data[i]);
	}
	return OK;
}

//主函数
int main()
{
	CompleteBinaryTree T;
	int much = 0;
	int choose = -1;
	int place = 0;
	TElemType e;
	while (choose != 0)
	{
		printf("input the chooes\n");
		scanf("%d", &choose);
		switch (choose)
		{
		case 1:
			if (InitTree(T) != NULL)
			{
				printf("InitTree sucess\n");
			}
			else
			{
				printf("InitTree fail\n");
			}
			break;
		case 2:
			InitTree(T);
			if (CreatTree(T)!=NULL)
			{
				printf("Creat scuess\n");
			}
			else
			{
				printf("Creat fail\n");
			}
			break;
		case 3:
			printf("input the place\n");
			scanf("%d", &place);
			printf("The value of this place is %d\n", GetNode(T, place, e));
			break;
		case 4:
			printf("input the place\n");
			scanf("%d", &place);
			printf("The value of this LeftChild is %d\n", GetLeftChild(T, place, e));
			break;
		case 5:
			printf("input the place\n");
			scanf("%d", &place);
			printf("The value of this LeftChild is %d\n", GetRightChild(T, place, e));
			break;
		case 6:
			printf("input the place\n");
			scanf("%d", &place);
			printf("The value of this GetParent is %d\n", GetParent(T, place, e));
			break;
		case 7:
			Print(T);
			break;
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值