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 6
Sample Output:
3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1
分析思路以及注意点
给出节点数,由于给出的是节点编号,所以可以用静态的方法去写,不必去设计data域以及指针
一个是在输入的过程中,scanf %c 格式可以读入换行符,使 scanf(“%*c”); 来读取换行符。
至于如何去找到根节点,可以开一个记录数组,在读取时进行更新,那个没出现的则不是子节点,必然是根节点。
至于反转二叉树:在二叉树的后序遍历过程的,交换节点。至于层序序列,可以用BFS去遍历。
下面给出代码
#include<bits/stdc++.h>
using namespace std;
const int maxn=10;
int n,num=0;
struct node
{
int lchild;
int rchild;
}Node[maxn];
bool root[maxn]={false};
int strTonum(char c)
{
if(c=='-') return -1;
else
{
root[c-'0']=true;
return c-'0';
}
}
int findroot()
{
for(int i=0;i<n;i++)
{
if(root[i]==false)
{
return i;
break;
}
}
}
void print(int root)
{
printf("%d",root);
num++;
if(num<n) printf(" ");
else printf("\n");
}
void BFS(int root)
{
queue<int> q;
q.push(root);
while(!q.empty())
{
int now=q.front();
q.pop();
print(now);
if(Node[now].lchild !=-1) q.push(Node[now].lchild);
if(Node[now].rchild!=-1) q.push(Node[now].rchild);
}
}
void inorder(int root)
{
if(root==-1) return;
inorder(Node[root].lchild);
print(root);
inorder(Node[root].rchild);
}
void postOrder(int root)
{
if(root==-1) return;
postOrder(Node[root].lchild);
postOrder(Node[root].rchild);
swap(Node[root].lchild,Node[root].rchild);
}
int main()
{
char lchild,rchild;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%*c%c %c",&lchild,&rchild);
Node[i].lchild=strTonum(lchild);
Node[i].rchild=strTonum(rchild);
}
int root=findroot();
postOrder(root);
BFS(root);
num=0;
inorder(root);
return 0;
}