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 6
Sample Output
3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1
题意
这题主要考察二叉树的层序遍历和中序遍历。层序遍历相当于BFS。其中注意字符串与数字的转换。
任何遍历都是从根节点开始,因此先要找出根结点,由于根结点没有父节点,所以在孩子结点说明表中未出现的就是根节点了,可用标记数组找出。
PS:为什么我觉得树的题目都很难啊,递归搞不懂,连着几道都得看柳神的答案,还总是看不懂o(╥﹏╥)o,但是看大家树的题目通过率又很高,还是我太菜了ε=(´ο`*)))唉
代码
#include <iostream>
#include <queue>
#include <string>
#include <vector>
using namespace std;
vector<string> lay,in;
bool book[11]= {false}; //标记每个数是否出现,未出现的就是根
struct node {
string left,right;
} Node[11];
void layOrder(string root) { //层序遍历
queue<string> q;
q.push(root);
while(!q.empty()) {
string now=q.front();
q.pop();
lay.push_back(now);
int id=stoi(now);
if(Node[id].right!="-") q.push(Node[id].right);
if(Node[id].left!="-") q.push(Node[id].left);
}
}
void inOrder(string root) { //中序遍历
int id=stoi(root);
if(Node[id].right!="-") inOrder(Node[id].right);
in.push_back(root);
if(Node[id].left!="-") inOrder(Node[id].left);
}
int main() {
int n;
scanf("%d",&n);
string l,r,s;
for(int i=0; i<n; i++) {
cin >> l >> r;
Node[i].left=l;
Node[i].right=r;
if(l!="-") book[stoi(l)]=true;
if(r!="-") book[stoi(r)]=true;
}
for(int i=0; i<n; i++) {
if(book[i]==false) {
s=to_string(i);
break;
}
}
layOrder(s); //遍历均要从根开始
inOrder(s);
for(int i=0; i<n; i++) {
printf("%s",lay[i].c_str());
if(i!=n-1) printf(" ");
}
printf("\n");
for(int i=0; i<n; i++) {
printf("%s",in[i].c_str());
if(i!=n-1) printf(" ");
}
return 0;
}