根據中序和后序還原二叉樹


首先二叉樹數據結構定義如下:

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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM