已知二叉树的中序序列和后序序列,求出这棵二叉树,将其存储在二叉链表中,并判断二叉树是否是完全二叉树。(C语言实现)

已知二叉树的中序序列和后序序列,求出这棵二叉树,将其存储在二叉链表中,并判断二叉树是否是完全二叉树。(要求C语言实现)

你题目的解答代码如下:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

//二叉树的存储表示 
typedef char TElemType;
typedef struct BiTNode {
    TElemType data;
    struct BiTNode *lchild, *rchild;    //左右孩子指针 
}BiTNode, *BiTree;


//inorder和postorder是二叉树的中序序列和后序序列
//lowin,highin是中序序列第一和最后结点的下标
//lowpost,highpost 是后序序列第一和最后结点的下标
//返回:二叉树的根结点指针 
BiTree CreateBitree(TElemType inorder[], TElemType postorder[], int lowin, int highin, int lowpost, int highpost)
{
    BiTree t = (BiTree)malloc(sizeof(BiTNode));
    t->data = postorder[highpost];//对于后序遍历,最后一个肯定是根节点
    t->lchild = t->rchild = NULL;//初始化根节点的左右孩子节点
    for (int pos = lowin; pos <= highin; pos++) {
        if (inorder[pos] == postorder[highpost]) {
            if(pos!=lowin) 
                t->lchild = CreateBitree(inorder, postorder, lowin, pos-1, lowpost, lowpost + pos - lowin-1);//左二叉树建立
            if(pos!=highin) 
                t->rchild = CreateBitree(inorder, postorder, pos + 1, highin, highpost-pos+lowin, highpost - 1);//右二叉树建立
            break;
        }
    }
    
    return t;
}

//按前序递归遍历二叉树 
void preorder(BiTree t)
{
    if (t)
    {
        printf("%c ", t->data);
        if (t->lchild)
            preorder(t->lchild);
        if (t->rchild)
            preorder(t->rchild);
    }
}

int main()
{
    TElemType in[] = "DBEAFCG";//中序 
    TElemType post[] = "DEBFGCA";    //后序 
    BiTree t;
    t = CreateBitree(in, post, 0, strlen(in) - 1, 0, strlen(post) - 1);
    preorder(t);
    system("pause");
}

如有帮助,望采纳!谢谢!