zoukankan      html  css  js  c++  java
  • POJ2255----Tree Recovery

    题目见此链接

    此题主要考察二叉树,根据给出先序遍历和中序遍历求后序遍历。
    代码如下:

    #include <iostream>
    #include <string>
    //#include <fstream>
    using namespace std;
    
    class Node{
        public:
            Node *left, *right;
            char data;
    };
    
    
    
    //AEFDHZMG
    //build tree
    void build(string preord, string inord, Node *root)
    {
        root->data = preord[0];
        if(preord.length() == 1)
        {
            return ;
        } 
        int rootLoc = inord.find(preord[0]);
        int rightLoc = preord.find(inord[rootLoc+1]);
        //cout << rightLoc << endl;
    
        //建立左子树 
        if(rootLoc > 0)
        {
            root->left = new Node();
            build(preord.substr(1, rootLoc), inord.substr(0, rootLoc), root->left);
        }
    
        //建立右子树 
        if(rightLoc > 0)
        {
            root->right = new Node();
            build(preord.substr(rootLoc + 1), inord.substr(rootLoc+1), root->right);
        }
    
    }
    
    //后序遍历二叉树
    void postorder(Node *root)
    {
        if(root->left)
        {
            postorder(root->left);
        }
        if(root->right)
        {
            postorder(root->right);
        }
        cout << root->data;
    }
    
    int main()
    {
        //ifstream in("data2255.in");
        string preord, inord, postord;
        while (cin >> preord >> inord)
        {
            Node *root = new Node();
            build(preord, inord, root);
            postorder(root);
            cout << endl;
            delete root;
        }
        return 0;
    }
    

      

  • 相关阅读:
    lightoj1140_数位dp
    lightoj1057_状压dp
    lightoj1068_数位dp
    lightoj1018_状压dp
    lightoj1217_简单dp
    lightoj1119_简单状压dp
    lightoj1037_状压dp
    lightoj1110_LCS并输出
    图论算法----最短路
    poj1182 食物链
  • 原文地址:https://www.cnblogs.com/topk/p/6580123.html
Copyright © 2011-2022 走看看