zoukankan      html  css  js  c++  java
  • BOJ二叉排序树的后序遍历

    二叉排序树的后序遍历
    Accept:28     Submit:223
    Time Limit:1000MS     Memory Limit:65536KB

    Description
    给定一个二叉排序树的前序遍历,输出其后序遍历。
    此二叉排序树中元素互不相同,节点的左儿子比节点小,右儿子比节点大。

    Input
    第一行有一个整数T,表示一共有T组测试数据。
    对于每组测试数据,第一行一个整数N,表示排序树中有N个元素(0 < N < = 100)。
    接下来有N个互不相同的整数,表示此二叉树的前序遍历序列。

    Output
    每组测试数据输出一行,包含N个整数,表示该组排序树的后序遍历,整数之间用空格隔开。

    Sample Input
    1
    3
    2 1 3

    Sample Output
    1 3 2

    #include<iostream>
    #include<cstdio>
    using namespace std;

    typedef struct node{
      int date;
      struct node * lchild,*rchild;       
    };
    node* root;
    int n;
    int cnt;
    void insert_tree(struct node *root, int e)
    {
      struct node *p=root;
      struct node *A=new node;
          A->date=e;
          A->lchild=NULL;
          A->rchild=NULL;
              while(1)
               {
                   if(e>p->date)
                   {
                     if(p->rchild!=NULL)
                      p=p->rchild;
                      else {p->rchild=A; break;}
                   }
                   else {
                          if(p->lchild!=NULL)
                           p=p->lchild;
                          else {p->lchild=A; break;}
                        }
                }
    }

    void pastorder(struct node *root)
    {
        if(root==NULL)
          return ;
        else {
                pastorder(root->lchild);
                pastorder(root->rchild);
                cout<<root->date;
                if(cnt++<n-1)
                  cout<<" ";
             }
    }
    int main()
    {
       int t,i,temp;
      
       cin>>t;
       while(t--)
       {
          scanf("%d",&n);
          scanf("%d",&temp);
          root=new node;
          root->date=temp;
          root->lchild=NULL;
          root->rchild=NULL;
          for(i=1; i<n; i++)
          {
            scanf("%d",&temp);
            insert_tree(root,temp);
          }
           cnt=0;
          pastorder(root);
          cout<<endl;        
       }
       //system("pause");
       return 0;
    }

  • 相关阅读:
    使用Jmeter进行http接口测试
    Jmeter分布式压测
    Jmeter进阶技能-数据库信息,传递参数
    解决Mac OS X 升级10.10(Yosemite)后ADT(Eclipse)无法找到真机
    bug list
    【adb工具包】Android的工具包log日志抓取
    【AI模型测试】运行过程中出错和解决方案:ImportError: cannot import name '_validate_lengths'
    【AI模型测试】anaconda linux 常用命令、安装源、清理缓存(转)
    【AI模型测试】skimage库安装(转)
    【Python学习】pip 常用命令及控制台怎么查看python 及pip 和已安装包版本号(转)
  • 原文地址:https://www.cnblogs.com/hpuwangjunling/p/3011366.html
Copyright © 2011-2022 走看看