1102 Invert a Binary Tree (25 point(s))

Matter

很标准的一道题目,考察了前序遍历,后序遍历,层序遍历,可以作为一个模板使用。

Code

#include<iostream>
#include<queue> 
#include<algorithm>
using namespace std;
const int MAXN = 15;

int num = 0 , n;
bool notroot[MAXN] = {false};

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

void print(int a){
	printf("%d" , a);
	num ++;
	if(num < n)	printf(" ");
	else printf("\n");
}

int strNum(char c){
	if(c == '-')	return -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;
		}
	}
}

void post_order(int root){
	if(root == -1)	return ;
	post_order(Node[root].lchild);
	post_order(Node[root].rchild);
	swap(Node[root].lchild , Node[root].rchild);	
}

void BFS(int root){
	queue<int> q;
	q.push(root);
	while(q.empty() == false){
		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 in_order(int root){
	if(root == -1)	return ;
	in_order(Node[root].lchild);
	print(root);
	in_order(Node[root].rchild);
}

int main(){

	//input
	scanf("%d" , &n);
	for(int i = 0 ; i < n ; i ++){
		char lc , rc;
		getchar();
		scanf("%c %c" , &lc , &rc);
		Node[i].lchild = strNum(lc);
		Node[i].rchild = strNum(rc);
	}
	
	//find the root of tree
	int root = find_root();
	
	//Use the post Order to invert the tree
	post_order(root);
	
	//print the level order
	BFS(root);
	
	//make the num to 0
	num = 0;
	
	//print the in order
	in_order(root);
	return 0;
} 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值