根据中序和后序还原二叉树

首先二叉树数据结构定义如下:

struct Node{
    Node* lchild;
    Node* rchild;
    char c;
}

思路如下:由后序遍历序列可得到根结点(即后序遍历最后一个结点),以根结点将中序遍历序列分为两个子序列。这样一来,就可以确定根结点下的左右子树的结点个数,那么在后序遍历序列可以看作根结点左子树序列+根结点右子树序列+根结点组成。由树的递归性可以对根结点左子树序列、根结点右子树序列进行相同操作。

具体实现起来需要更多细节,设定两序列长度均为size,后序遍历序列为post[size],中序遍历序列为in[size],在递归过程中后序遍历序列区间为[postL, postR],中序遍历序列区间为[inL, inR],由上述分析可以知道,在这一递归阶段中,根结点为post[postR],。接着在中序遍历序列中寻找位置pos,使in[pos] = post[postR],这样这一递归阶段中左子树结点数量为k - inL, 进入下一递归阶段时,左子树后序遍历序列变为[postL, postL + k - inL - 1],中序遍历序列变为[inL, k - 1];右子树后序遍历序列变为[postL + k - inL, postR - 1],中序遍历序列变为[k + 1, inR];

代码描述如下:

const int size = 100    //暂定序列长度最大为一百

char post[size], in[size];

Node* create(int postL, int postR, int inL, int inR){
    if(postL > postR) return NULL;
    Node* root = new Node;
    root->c = post[postR];
    int pos;
    for(pos = inL; pos <= inR; pos++){
        if(in[pos] == post[postR]) break;
    }
    root->lchild = create(postL, postL + k - inL - 1, inL, k - 1);
    root->rchild = create(postL + k - inL, postR - 1, k + 1, inR);
    return root;
}

 

posted @ 2019-03-21 13:34  苏安  阅读(3040)  评论(1编辑  收藏  举报