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

      

  • 相关阅读:
    文件比较运算符
    中山慧海人才市场9月份 现场招聘会预告
    80后智能科技公司诚聘业务人员
    元豪路灯厂诚聘
    对Discuz的简单认识
    discuz阅读权限的设置作用
    个人对织梦系统的认识
    awvs的用法
    cain使用方法
    CCNA笔记(1)
  • 原文地址:https://www.cnblogs.com/topk/p/6580123.html
Copyright © 2011-2022 走看看