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

题意:给定一棵二叉树,其结点编号已经给定,从0开始输入结点的左右孩子结点编号。若为-则为空。输入完成后进行反转二叉树,即交换每个结点的左右孩子结点。

思路:由于要进行反转二叉树,所以利用静态二叉树比较好进行解决。因为要输入每个结点的孩子结点,而根节点不是任何一个结点的孩子,所以根节点在输入时是不会出现的,以此为根据进行判断根节点。而进行二叉树的左右交换时,使用后序遍历交换比较方便(左右根)。
AC代码

#include<stdio.h>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn=110;
struct node{
	int lchild,rchild;
}Node[maxn];//静态二叉树结构
bool notroot[maxn]={false};//用以确定二叉树根节点出现与否
int n,num=0;
void print(int id){//输出格式的表达
	printf("%d",id);
	num++;//统计节点数
	if(num<n)printf(" ");
	else printf("\n");
}
void inorder(int root){//中序遍历
	if(root==-1){
		return;
	}
	inorder(Node[root].lchild);
	print(root);
	inorder(Node[root].rchild);
}
void BFS(int root){//层次遍历
	queue<int>q;
	q.push(root);
	while(!q.empty()){
		int k=q.front();
		q.pop();
		print(k);
		if(Node[k].lchild!=-1){
			q.push(Node[k].lchild);
		}
		if(Node[k].rchild!=-1){
			q.push(Node[k].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 str_to_num(char c){//对空节点的处理
	if(c=='-')return -1;//将'-'转换为-1
	else{
		notroot[c-'0']=true;
		return c-'0';
	}
}
int find_root(){//寻找根节点
	for(int i=0;i<n;i++){
		if(notroot[i]==false){
			return i;
		}
	}
}
int main(){
	scanf("%d",&n);
	char c1,c2;
	for(int i=0;i<n;i++){//从0节点开始输入
		getchar();
		scanf("%c %c",&c1,&c2);
		Node[i].lchild=str_to_num(c1);
		Node[i].rchild=str_to_num(c2);
	}
	int root=find_root();
	postorder(root);
	BFS(root);
	num=0;
	inorder(root);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值