1 题目

102 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

2 解析

  • 题意:给出二叉树每个结点的左右孩子结点的编号,求反转二叉树后,输出层序和中序
  • 思路:
  • 1,用二叉树的静态方法创建二叉树
  • 2,用后序遍历反转(递归遍历后交换左右结点)二叉树
  • 3,层序、中序输出反转后的二叉数

3 参考代码

#include 
#include
#include

using std::queue;
using std::swap;

const int MAXN = 20;
bool notRoot[MAXN] = {false};
int num = 0;
int N;

struct node
{
int lchild;
int rchild;
}Node[MAXN];

int strToNum(char c){
if(c == '-'){
return -1;
}else{
notRoot[c - '0'] = true;
return c - '0';
}
}

int findRoot(){
for (int i = 0; i < N; ++i)
{
if(notRoot[i] == false){
return i;
}
}
}

void Reverse(int root){
if(root == -1){
return;
}

Reverse(Node[root].lchild);
Reverse(Node[root].rchild);
swap(Node[root].lchild, Node[root].rchild);
}

void print(int root){
printf("%d", root);
num++;

if(num < N){
printf(" ");
}else{
printf("\n");
}

}


void layerorder(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);
}

int main(){
scanf("%d", &N);

char lchild, rchild;
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();

Reverse(root);

layerorder(root);
num = 0;
inorder(root);

return 0;
}