zoukankan      html  css  js  c++  java
  • 由先序遍历+中序遍历推出后序遍历

    #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);
        } 
    }
  • 相关阅读:
    权限管理命令
    常用命令2
    常用命令1
    queue
    poj 3984
    L3-008 喊山 (30 分)
    常州大学新生寒假训练会试 I 合成反应
    dfs 的全排列
    poj 1154
    hdu 1241
  • 原文地址:https://www.cnblogs.com/juanzhi/p/12976771.html
Copyright © 2011-2022 走看看