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

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

猜你喜欢

转载自www.cnblogs.com/juanzhi/p/12976771.html