1.将二叉树转换为顺序存储结构,按完全二叉树形式存储,无元素的结点当做虚结点。按层次顺序遍历二叉树,设根结点编号为0,设置一队列,将结点及其序号入队。出队时将结点及其编号写入顺序存储结构。
#include "stdafx.h"#includeusing namespace std;typedef struct BTreeNode{ int data; struct BTreeNode *lchild,*rchild;}BTree;int _tmain(int argc, _TCHAR* argv[]){ return 0;}typedef struct{ BTree *node; int num;}tnode;void BTreeToSeqt(BTree *t,char s[]){ tnode q[100]; tnode tq; int front=0,rear=0; BTree *p; if(t==NULL)exit(0); for(int i=0;i<100;i++) { s[i]='#';//虚结点 tq.node=t;tq.num=1;q[++rear]=tq;//根结点入队 while(front data; if(p->lchild)//左子女入队 { tq.node=p->lchild; tq.num=2*i; q[++rear]=tq; } if(p->rchild)//右子女入队 { tq.node=p->rchild; tq.num=2*i+1; q[++rear]=tq; } } }}
2.顺序结构建立二叉树,有些结点是虚结点
#include "stdafx.h"#includeusing namespace std;typedef struct BTreeNode{ int data; struct BTreeNode *lchild,*rchild;}BTree;int _tmain(int argc, _TCHAR* argv[]){ return 0;}typedef struct{ BTree *node; int num;}tnode;void create(BTree *t,char s[],int length)//length为二叉树数组长度{ tnode q[100]; tnode tq; int front=0,rear=0; t=(BTree*)malloc(sizeof(BTreeNode)); t->data=s[0];//根结点存在s[0] tq.node=t;tq.num=1; q[0]=tq;//入队 while(front!=rear) { front++; tq=q[front]; BTree *p=tq.node; int i=tq.num;//出队,取出结点及编号 if(2*i>length||s[2*i]=='#')//左子树为空 { p->lchild=NULL; } else { p->lchild=(BTree*)malloc(sizeof(BTreeNode)); p->lchild->data=s[2*i]; tq.node=p->lchild;tq.num=2*i; rear++; q[rear]=tq;//左子女结点及其编号入队 } if(2*i+1>length||s[2*i+1]=='#')//右子树为空 { p->rchild=NULL; } else { p->rchild=(BTree*)malloc(sizeof(BTreeNode)); p->rchild->data=s[2*i+1]; tq.node=p->rchild;tq.num=2*i+1; rear++; q[rear]=tq;//右子女结点及其编号入队 } }}