• 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;
    }
  • 相关阅读:
    c++中ctype常用函数总结(isprint isblank..)
    c++的const总结(转)
    c++重载输入输出运算符
    c++中的友元重载
    c++函数模板二栈实现
    c++函数模板1
    c++中IO输入输出流总结<二>
    c++中IO输入输出流总结<一>
    四层与七层得区别(转)
    ORACLE操作
  • 原文地址:https://www.cnblogs.com/kimsimple/p/6905032.html
Copyright © 2020-2023  润新知