给出后序遍历和中序遍历的结果 可以得到前序遍历和层序遍历。
思路就是把中序遍历和后序遍历的结果存到数组中 再通过数组构建二叉树
beetree create(int postl,int postr,int inl,int inr)
{
if(postl>postr) return NULL;
beetree root = (beetree)malloc(sizeof(struct node));
root->data = post[postr];
int k;
for(k=inl;k<inr;k++){
if(in[k]==post[postr]) break;
}
int numleft = k-inl;
root->lchild = create(postl,postl+numleft-1,inl,k-1);
root->rchild = create(postl+numleft,postr-1,k+1,inr);
return root;
}
postl前序遍历左端点。
intr 后序遍历的右端点。
root->data = post[postr];
根节点
for(k=inl;k<inr;k++){
if(in[k]==post[postr]) break;
}
int numleft = k-inl;
找到根节点在中序遍历的位置
numleft 左子树的长度.
所以左子树的区间是【inl,numleft+inl-1】
右子树的区间是【inl+numleft,inr-1】
中序遍历的左子树区间是【inl,k-1】
右子树区间是【k+1,lnr】
前序遍历
void preorder(beetree bt){
if(bt){
if(space) printf(" ");
printf("%d",bt->data);
space = 1;
preorder(bt->lchild);
preorder(bt->rchild);
}
}
层序遍历
void leaveorder(beetree root){
queue<beetree>qu;
qu.push(root);
int space = 0;
while(qu.empty()!=true){
beetree node =qu.front();
qu.pop();
if(space) printf(" ");
printf("%d",node->data);
space = 1;
if(node->lchild) qu.push(node->lchild);
if(node->rchild) qu.push(node->rchild);
}
}