由先序遍歷+中序遍歷推出后序遍歷


 

 

 

#include <iostream>
#include <cstdio>
#include <algotithm>

using namespace std;

struct TreeNode{
    char data;
    TreeNode* leftChild;
    TreeNode* rightChild;
    //構造函數
    TreeNode(char c):data(c),leftChild(nullptr),rightChild(nullptr){
    } 
};

//先序+中序 =>后序 
TreeNode* Build(string preOrder,string inOrder){
    if(preOrder.size() == 0){
        return nullPtr; 
    } 
    char c = preOrder[0];
    TreeNode* root= new TreeNode(c);
    int position = inOrder(c);
    root->leftChild = Build(preOrder.substr(1,position),inOrder(0,position));
    root->rightChild = Build(preOrder.substr(position + 1),inOrder(position + 1));
    return root;
}

//后序遍歷
void PostOrder(TreeOrder* root){
    if(root == nullptr){
        return;
    }
    PostOrder(root->leftChild);
    PostOrder(root->rightChild);
    printf("%c",root->data);
} 

int main(){
    string preOrder,inOrder;
    while(cin>>preOrder>>inOrder){
        TreeNoder* root = Build(preOrder,inOrder);
        PostOrder(root);
    } 
}

 


免責聲明!

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



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