zoukankan      html  css  js  c++  java
  • HDU1710---树(知前序遍历与中序遍历 求后序遍历)

     知前序遍历与中序遍历 求后序遍历

    #include<iostream>
    #include<cstring>
    #include<queue>
    #include<cstdio>
    using namespace std;
    bool fist;
    const int maxn=1005;
    struct tree_node
    {
      int value;
      tree_node* leftchild;
      tree_node* rightchild;
      tree_node()
      {
        leftchild=NULL;
        rightchild=NULL;
      }
    };
    /**
        根据中序遍历,前序遍历建树
        递归 忽略细节  深入至所有结点建立
    */
    tree_node* build_tree(int pre[],int in[],int length)
    {
      if(length==0)return NULL;///终止条件
      tree_node* temp = new tree_node;
      int pos;
      for(pos=0;pos<length;pos++)///找到根节点->然后根据中序遍历把左子树和右子树分开
      {
        if(in[pos]==pre[0])break;
      }
      temp->value=pre[0];
      temp->leftchild=build_tree(pre+1,in,pos);
      temp->rightchild=build_tree(pre+pos+1,in+pos+1,length-pos-1);
      return temp;
    }
    
    void postOrder(tree_node* root)
    {
        if(root!=NULL)
        {
            postOrder(root->leftchild);
            postOrder(root->rightchild);
            if(!fist)///根节点输出
            {
              cout<<root->value;
              fist=true;
            }
            else
                cout<<" "<<root->value;
        }
    }
    int main()
    {
      int n;
      int pre[maxn],in[maxn];
      while(scanf("%d",&n)==1)
      {
        fist=false;
        ///input
        for(int i=0;i<n;i++)scanf("%d",&pre[i]);
        for(int i=0;i<n;i++)scanf("%d",&in[i]);
        ///solve
        tree_node* tree=build_tree(pre,in,n);
        postOrder(tree);
        cout<<endl;
      }
      return 0;
    }
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    
    const int maxn = 1000 + 5;
    int pre[maxn], in[maxn], n, pos[maxn];
    
    void creat(int l, int r, int L, int R) {
    
        if (L == R) {
            printf("%d ", in[L]);
            return;
        }
    
        int id = pos[pre[l]];///in中父节点位置
        if(id > L)  creat(l + 1, l + id - L, L, id - 1);//边界, 左
        if(id < R)  creat(l + 1 + id - L, r, id + 1, R);//
    
        printf("%d%s", in[id], l == 1 ? "
    " : " ");
    }
    
    int main() {
    #ifndef ONLINE_JUDGE
        freopen("in.txt", "r", stdin);
    #endif
    
        while (~scanf("%d", &n)) {
            for (int i = 1; i <= n; ++i) scanf("%d", &pre[i]);
            for (int i = 1; i <= n; ++i) {
                scanf("%d", &in[i]);
                pos[in[i]] = i;
            }
            creat(1, n, 1, n);
        }
    
        return 0;
    }
  • 相关阅读:
    java Socket Tcp 浏览器和服务器(二)
    java Socket Tcp 浏览器和服务器(一)
    java Socket Tcp示例三则(服务端处理数据、上传文件)
    java Socket Udp聊天
    centos 图形界面和命令行界面切换
    python 文件中的中文编码解决方法
    PostgreSQL与MySQL比较(转)
    Python 的开发环境
    Windows 下 pip和easy_install 的安装与使用
    Linux 下的下载文件命令
  • 原文地址:https://www.cnblogs.com/kimsimple/p/6905032.html
Copyright © 2011-2022 走看看