题目链接:http://www.patest.cn/contests/pat-a-practise/1102
题面:
1102. Invert a Binary Tree (25)
The following is from Max Howell @twitter:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can't invert a binary tree on a whiteboard so fuck off.
Now it's your turn to prove that YOU CAN invert a binary tree!
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (<=10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N-1. Then N lines follow, each corresponds to a node from 0 to N-1, and gives the indices of the left and right children of the node. If the child does not exist, a "-" will be put at the position. Any pair of children are separated by a space.
Output Specification:
For each test case, print in the first line the level-order, and then in the second line the in-order traversal sequences of the inverted tree. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.
Sample Input:8 1 - - - 0 - 2 7 - - - - 5 - 4 6Sample Output:
3 7 2 6 4 0 5 1 6 5 7 4 3 2 0 1
题目大意:
给定一棵树,将其反转后,输出层序遍历和中序遍历的结果。
解题:
反转操作很简单,建树的时候,交换左右节点即可。层序遍历用bfs,中序遍历用dfs。一开始想为什么数据只有10,这么小。其实这也是一个坑点,如果大于10,那么读入的时候就肯定坑很多人。
代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#define arraysize 100010
using namespace std;
struct node
{
int le,ri,id;
}nd[12];
int lo[12],io[12];
bool vis[12];
queue <int> qe;
void level_t(int r)
{
int cnt=0,tmp;
qe.push(r);
while(!qe.empty())
{
tmp=qe.front();
qe.pop();
lo[cnt++]=tmp;
if(nd[tmp].le>=0)
qe.push(nd[tmp].le);
if(nd[tmp].ri>=0)
qe.push(nd[tmp].ri);
}
}
int p=0;
void inorder_t(int r)
{
if(nd[r].le>=0)
inorder_t(nd[r].le);
io[p++]=r;
if(nd[r].ri>=0)
inorder_t(nd[r].ri);
}
int main()
{
int n,root;
scanf("%d",&n);
char a,b;
memset(vis,0,sizeof(vis));
for(int i=0;i<n;i++)
{
getchar();
scanf("%c %c",&a,&b);
nd[i].id=i;
if(a>='0'&&a<='9')
{
nd[i].ri=a-'0';
vis[a-'0']=1;
}
else
nd[i].ri=-1;
if(b>='0'&&b<='9')
{
nd[i].le=b-'0';
vis[b-'0']=1;
}
else
nd[i].le=-1;
}
for(int i=0;i<n;i++)
{
if(!vis[i])
root=i;
}
level_t(root);
inorder_t(root);
printf("%d",lo[0]);
for(int i=1;i<n;i++)
printf(" %d",lo[i]);
printf("\n");
printf("%d",io[0]);
for(int i=1;i<n;i++)
printf(" %d",io[i]);
printf("\n");
return 0;
}