九度oj题目1521:二叉树的镜像

题目1521:二叉树的镜像

时间限制:1 秒

内存限制:128 兆

特殊判题:

提交:2061

解决:560

题目描述:

输入一个二叉树,输出其镜像。

输入:

输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行为一个整数n(0<=n<=1000,n代表将要输入的二叉树节点的个数(节点从1开始编号)。接下来一行有n个数字,代表第i个二叉树节点的元素的值。接下来有n行,每行有一个字母Ci。
Ci=’d’表示第i个节点有两子孩子,紧接着是左孩子编号和右孩子编号。
Ci=’l’表示第i个节点有一个左孩子,紧接着是左孩子的编号。
Ci=’r’表示第i个节点有一个右孩子,紧接着是右孩子的编号。
Ci=’z’表示第i个节点没有子孩子。

输出:

对应每个测试案例,
按照前序输出其孩子节点的元素值。
若为空输出NULL。

样例输入:
7
8 6 10 5 7 9 11
d 2 3
d 4 5
d 6 7
z
z
z
z
样例输出:
8 10 11 9 6 7 5

注意:对于单个字符输入,不要用scanf!!

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <string>
 4 #include <queue>
 5 #include <stack>
 6 #include <iostream>
 7 using namespace std;
 8 struct node{
 9     int l,r,v;
10 };
11 node nodes[1005];
12 void reserve(int num){
13     if(nodes[num].l)
14     reserve(nodes[num].l);
15     if(nodes[num].r)
16     reserve(nodes[num].r);
17     int nn=nodes[num].l;
18     nodes[num].l=nodes[num].r;
19     nodes[num].r=nn;
20 }
21 void prefind(int num){
22     if(!num)
23         return;
24     if(num>1)
25     printf(" ");
26     printf("%d",nodes[num].v);
27     prefind(nodes[num].l);
28     prefind(nodes[num].r);
29 }
30 int main(){
31     //freopen("D:\INPUT.txt","r",stdin);
32     int n;
33     while(scanf("%d",&n)!=EOF){
34         int i;
35         for(i=1;i<=n;i++){
36             scanf("%d",&nodes[i].v);
37         }
38         //建树
39         for(i=1;i<=n;i++){
40             char c;
41             cin>>c;//对于输入单个字符,不要用scanf!!!
42             //scanf("%c",&c);
43             if(c=='d'){
44                 scanf("%d %d",&nodes[i].l,&nodes[i].r);
45             }else{
46                 if(c=='l'){
47                     scanf("%d",&nodes[i].l);
48                     nodes[i].r=0;
49                 }
50                 else{
51                     if(c=='r'){
52                         scanf("%d",&nodes[i].r);
53                         nodes[i].l=0;
54                     }
55                     else{//c=='z'
56                         nodes[i].l=0;
57                         nodes[i].r=0;
58                     }
59                 }
60             }
61         }
62         if(!n){
63             printf("NULL
");
64         }
65         else{
66             reserve(1);//镜像
67             prefind(1);//前序遍历
68         }
69     }
70     return 0;
71 }
原文地址:https://www.cnblogs.com/Deribs4/p/4647723.html