算法介绍在代码注释上,时间有限,未测试^^
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int N=1010;
typedef int ElemType;
typedef struct Forest{
int data;
Forest *child[N];
}Forest;
typedef struct Tree{
int data;
Tree *left,*right;
}Tree;
Tree *ForestToBiTree(Forest *F){ //树转二叉树
if(F==NULL) return NULL;
Tree *T=new Tree;
T->data=F->data;
T->left=T->right=NULL;
queue<Forest*>fq;
queue<Tree*>tq;
fq.push(F); //树和二叉树同时存入队列
tq.push(T);
while(!fq.empty()){
Forest *f=fq.front(); fq.pop(); //同时取出
Tree *t=tq.front(); tq.pop(); //每次操作都是对树一个节点的孩子进行操作
Tree *p=NULL;
for(int i=0;i<N;i++){
if(f->child[i]==NULL) break;
Tree *node=new Tree;
node->data=f->child[i]->data;
node->left=node->right=NULL;
if(i==0){
t->left=node; //树第一个节点为二叉树的左孩子
}
else {
p->right=node; //其余节点为上面左节点的右孩子
}
p=node;
fq.push(f->child[i]);
tq.push(node);
}
}
return T;
}
Forest *BiTreeToForest(Tree *T){
if(T==NULL) return NULL;
Forest *F=new Forest;
F->data=T->data;
F->child[0]=NULL;
queue<Tree*>tq;
queue<Forest*>fq;
tq.push(T);
fq.push(F); //树和二叉树同时存入队列
while(tq.empty()){
Tree *t=tq.front(); tq.pop(); //每次操作都是对树一个节点的孩子进行操作
Forest *f=fq.front(); fq.pop(); //同时取出
int i=0;
if(t->left){ //分别将二叉树节点的左孩子和左孩子后面的右孩子作为树的孩子节点
Forest *p=new Forest;
p->data=t->left->data; p->child[0]=NULL;
f->child[i++]=p;
fq.push(p);
tq.push(t->left);
}
t=t->left->right;
while(t){
Forest *p=new Forest;
p->data=t->data; p->child[0]=NULL;
f->child[i++]=p;
fq.push(p);
tq.push(t);
t=t->right;
}
}
return F;
}
int main()
{
return 0;
}