C++将链表二叉树转化为顺序表二叉树

/*
#include<iostream>
using namespace std;
#define InitSize 20
typedef int TElemType;

typedef struct node{
	struct node* lchild, *rchild;
	TElemType data;
}BinNode;

typedef struct {
	BinNode tnode[InitSize];
	int curSize, maxSize;
}BinTree;

void TreeInit(BinTree&BT)
{
	BT.curSize = 0;
	BT.maxSize = InitSize;
}

void CreateBinTree(BinTree&BT,TElemType ch[],int n)
{
	TreeInit(BT);
	if (BT.maxSize < n)return;
	for (int i = 0;i < n;i++)
	{
		BT.tnode[i].data = ch[i];
		int parent = (i - 1) / 2;
		if ( parent>= 0)
		{
			if (i % 2)
				BT.tnode[parent].lchild = &BT.tnode[i];
			else
				BT.tnode[parent].rchild = &BT.tnode[i];
		}
	}
	BT.curSize = n;
}

int main()
{
	TElemType ch[10] = { 1,2,3,4,5,6,7,8,9,10 };
	BinTree BT;
	CreateBinTree(BT, ch, 10);
	system("pause");
}

*/


#include<iostream>
using namespace std;
typedef int TElemType;
#define InitSize 20

typedef struct node {
	TElemType data;
	struct node*lchild, *rchild;
}TNode;

typedef struct {
	TNode tnode[InitSize];
	int curSize, maxSize;
}Tree;

typedef struct {
	TElemType elem[InitSize];
	int curSize, maxSize;
}SeqTree;

void CreateTree(TNode*&BT, TElemType ch[], int n,int maxSize)
{
	BT = new TNode;
	BT->data = ch[n];
	if (2 * n + 1 < maxSize)
		CreateTree(BT->lchild, ch, 2 * n + 1, maxSize);
	else BT->lchild = NULL;
	if (2 * n + 2 < maxSize)
		CreateTree(BT->rchild, ch, 2 * n + 2, maxSize);
	else BT->rchild = NULL;
}

void DispTree(TNode*&root)
{
	TNode*S[InitSize];
	int front = 0, rear = 0;
	rear = (rear + 1) % InitSize;
	S[rear] = root;
	while (front != rear)
	{
		front = (front + 1) % InitSize;
		TNode*first = S[front];
		cout << first->data;
		if (first->lchild != NULL)
		{
			rear = (rear + 1) % InitSize;
			S[rear] = first->lchild;
		}
		if (first->rchild != NULL)
		{
			rear = (rear + 1) % InitSize;
			S[rear] = first->rchild;
		}
	}
}

void TreeToSeq(TNode*BT,SeqTree&ST,int n)
{
	ST.elem[n] = BT->data;
	ST.curSize++;
	if (BT->lchild != NULL)
		TreeToSeq(BT->lchild, ST, 2 * n + 1);
	if (BT->rchild != NULL)
		TreeToSeq(BT->rchild, ST, 2 * n + 2);
}

int main()
{
	TNode*BT;
	SeqTree ST;
	ST.maxSize = InitSize;
	ST.curSize = 0;
	TElemType ch[] = { 1,2,3,4,5,6,7,8,9,10 };
	CreateTree(BT, ch, 0, 10);
	DispTree(BT);
	TreeToSeq(BT, ST, 0);
	for (int i = 0;i < ST.curSize;i++)
		cout << ST.elem[i] << ' ';
	system("pause");
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值