坦然玲子  
第三题:二叉树前序遍历
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 }

 

posted on 2013-04-09 23:07  坦然玲子  阅读(223)  评论(0编辑  收藏  举报