PAT A1102 Invert a Binary Tree

#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 11;

struct node{ //二叉树的静态写法 
	int lchild,rchild;
}Node[maxn];

bool notRoot[maxn] = {false};//记录是否不是根结点,初始均是根结点 
int n, num = 0; //n为结点个数,num为当前已经输出的结点个数
//print函数输出结点id的编号
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 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 postOrder(int root) {
	if(root == -1) return;
	postOrder(Node[root].lchild);
	postOrder(Node[root].rchild);
	swap(Node[root].lchild,Node[root].rchild); //交换左右孩子结点 
}

//将输入的字符转换为-1或者结点编号
int strToNum(char c) {
	if( c == '-') return -1;//'-' 表示没有孩子结点,记为-1 
	else{
		notRoot[c-'0'] = true; //标记该结点肯定不是根结点
		return c - '0' ;//返回结点编号 
	}
}

//寻找根结点编号 
int findRoot() {
	for(int i=0;i<n;i++){
		if(notRoot[i] == false) return i;
	}
}

int main() {
	char lchild,rchild;
	scanf("%d",&n);
	for(int i=0;i<n;i++){
		getchar();
		scanf("%c %c",&lchild,&rchild);//中间必须记得要有空格分开 
		//以上两句也可以用 scanf("%*c%c %c",&lchild,&rchild);代替 
		Node[i].lchild = strToNum(lchild);
		Node[i].rchild = strToNum(rchild);
	}
	int root = findRoot(); //获取根结点编号 
	postOrder(root); //后序遍历,用以反转二叉树 
	BFS(root) ; //输出层序遍历结果
	num = 0;//已输出的结点个数置0 
	inOrder(root); // 输出中序遍历序列 
	return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值