/*
#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");
}
C++将链表二叉树转化为顺序表二叉树
最新推荐文章于 2024-07-25 10:09:27 发布