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
思路分析:
类似此题的建树可以直接遍历三次结点,即可完成结点初始化、建树并标记孩子标志位、找出根节点
但此题要建立的为逆转二叉树,只要在建树时默认把输入第一列当作是右孩子,第二列当作左孩子处理即可
之后的层序遍历,中序遍历为常规写法
注意输入的处理(数字 和 ‘-’)
#include<cstdio>
#include<iostream>
#define MAX 20
typedef struct NODE{
int data;
struct NODE *left;
struct NODE *right;
int isChild;
}NODE;
int n;
NODE *node[MAX];
void levelorder(NODE *root)
{
int temp1=0;
NODE *que[MAX];
int front=-1,rear=-1;
que[++rear]=root;
while(front!=rear)
{
NODE *node=que[++front];
if(node->left!=NULL)
{
que[++rear]=node->left;
}
if(node->right!=NULL)
{
que[++rear]=node->right;
}
if(temp1==n-1)printf("%d",node->data);
else
{
printf("%d ",node->data);
temp1++;
}
}
}
int temp2=0;
void inorder(NODE *root)
{
if(root==NULL)return;
inorder(root->left);
if(temp2==n-1)printf("%d",root->data);
else
{
printf("%d ",root->data);
temp2++;
}
inorder(root->right);
}
int main()
{
scanf("%d",&n);
for(int i=0;i<n;i++)
{
NODE *newNode=new NODE;
newNode->left=NULL;
newNode->right=NULL;
newNode->isChild=0;
newNode->data=i;
node[i]=newNode;
}
for(int i=0;i<n;i++)
{
int left=-1;
int right=-1;
scanf("%d ",&right);
// printf("**%d**",right);
scanf("%d",&left);
// printf("**%d**",left);
if(right!=-1)
{
node[i]->right=node[right];
node[right]->isChild=1;
}
if(left!=-1)
{
node[i]->left=node[left];
node[left]->isChild=1;
}
}
NODE *root=new NODE;
for(int i=0;i<n;i++)
{
if(node[i]->isChild==0)
{
root=node[i];
break;
}
}
levelorder(root);
printf("\n");
inorder(root);
}