zoukankan      html  css  js  c++  java
  • BOJ第三题:二叉树前序遍历

    第三题:二叉树前序遍历
    Accept:15     Submit:33
    Time Limit:1000MS     Memory Limit:65536KB
    Description
    给定一棵有n个结点的二叉树,结点的编号为0~n-1。请你编写程序输出二叉树的前序遍历序列。

    Input
    输入的第一行是一个正整数t(1 < t < 20),表示有t组测试用例。
    对于每组测试用例,第一行是一个整数n(0 < n < 20),表示二叉树结点个数。第二行是一个数r(0≤r≤n-1),二叉树根结点的编号。
    后面有n-1行,表示二叉树n-1条边的信息。每行三个数a,b,c,三个数间由空格隔开,其中0≤a,b≤n-1且a≠b, c为0或1。a表示边的起点,b表示边的终点。如果c为0,表示b是a的左儿子;如果c为1,表示b是a的右儿子。


    Output
    对于每组测试用例输出一行,即:该二叉树的前序遍历序列,两个节点编号之间留一个空格。

    Sample Input

    2
    3
    2
    2 0 0
    2 1 1
    7
    0
    0 1 0
    0 2 1
    1 3 0
    1 4 1
    2 5 0
    2 6 1


    Sample Output

    2 0 1
    0 1 3 4 2 5 6


    Hint
    由于是计算机自动判题,请严格按照题目的描述输入输出,不要有任何多余的字符出现,尤其是输出行的行首和行尾都不要有多余的空格
    View Code
     1 #include<iostream>
     2 #include<cstdio>
     3 using namespace std;
     4 typedef struct node{
     5      int  id;
     6      struct node *lchild,*rchild;          
     7 };
     8 node *root;
     9 node tree[22];
    10 int cnt,n;
    11 void add_edge(int a, int b, int c)
    12 {
    13     if(c)
    14        tree[a].rchild=&tree[b];
    15        else   tree[a].lchild=&tree[b];       
    16 }
    17 void preorder(struct node *root)
    18 {
    19    if(root==NULL)
    20       return ;
    21    else {
    22           cout<<root->id;
    23           if(cnt++<n-1)
    24            cout<<" ";
    25            preorder(root->lchild);
    26            preorder(root->rchild);
    27         }     
    28 }
    29 int main()
    30 {
    31    int t,r,a,b,c,i;
    32    
    33    scanf("%d",&t);
    34    while(t--)
    35    {
    36       scanf("%d",&n);
    37       cin>>r;
    38       for(i=0; i<n; i++)
    39        {
    40          tree[i].id=i;
    41          tree[i].lchild=NULL;
    42          tree[i].rchild=NULL;        
    43        } 
    44        for(i=0; i<n-1; i++)
    45        {
    46           scanf("%d%d%d",&a,&b,&c);
    47           add_edge(a,b,c);         
    48        }  
    49        struct node *root=&tree[r];
    50        cnt=0;
    51        preorder(root);
    52        cout<<endl;    
    53    } 
    54    system("pause");
    55    return 0;   
    56 }
  • 相关阅读:
    启动MySql提示:The server quit without updating PID file(…)失败
    Linux环境安装git
    Linux环境下安装jenkins
    Linux 环境下安装Maven
    阿里云服务器tomcat启动慢解决方案
    Linux环境安装redis
    Linux环境安装nginx
    Paxos算法细节详解(一)--通过现实世界描述算法
    Nginx的配置详解
    Javascript中DOM详解与学习
  • 原文地址:https://www.cnblogs.com/hpuwangjunling/p/3011383.html
Copyright © 2011-2022 走看看