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

思路:

反转一棵二叉树,给出原二叉树的每个结点的左右孩子,输出它的层序和中序遍历

注意不论是层序遍历还是中序遍历,要检查左右孩子是否存在。

字符读取要用getchar()读掉回车

C++:

#include "queue"
#include "iostream"
using namespace std;
struct node
{
	int id;
	int lchid,rchid;
};
node nodes[12];
int l[12],in[12];
bool book[12]={false};
int n,index=0,indexi=0;
void level(int root){
	queue<node> q;
	q.push(nodes[root]);
	while (!q.empty())
	{
		node temp=q.front();
		l[index++]=temp.id;
		q.pop();
		if (temp.lchid!=-1)q.push(nodes[temp.lchid]);
		if (temp.rchid!=-1)q.push(nodes[temp.rchid]);
	}
}
void inorder(int root){
	if (nodes[root].lchid==-1&&nodes[root].rchid==-1){in[indexi++]=nodes[root].id;return;}
	if (nodes[root].lchid!=-1)inorder(nodes[root].lchid);
	in[indexi++]=nodes[root].id;
	if (nodes[root].rchid!=-1)inorder(nodes[root].rchid);
}
int main(){
	int root;
	scanf("%d",&n);
	getchar();
	for (int i=0;i<n;i++)
	{
		char left,right;
		scanf("%c %c",&right,&left);
		getchar();
		nodes[i].rchid=(right=='-')?(-1):(right-'0');
		nodes[i].lchid=(left=='-')?(-1):(left-'0');
		nodes[i].id=i;
		if(nodes[i].lchid != -1)
			book[nodes[i].lchid] = true;
		if(nodes[i].rchid!= -1)
			book[nodes[i].rchid] = true;
	}
	for (int i=0;i<n;i++)
		if (book[i]==false)root=i;
	level(root);
	inorder(root);
	for (int i=0;i<n;i++){
		printf("%d",l[i]);
		if (i!=n-1)printf(" ");
		else
			printf("\n");
	}
	for (int i=0;i<n;i++){
		printf("%d",in[i]);
		if (i!=n-1)printf(" ");
		else
			printf("\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ysq96/article/details/81321153
今日推荐