PAT 甲级 1102 Invert a Binary Tree (25 分)

Note

  • 二叉树
  • 一开始没有读懂题…(太菜了orz)
  • input:编号(第几行)代表根节点与左右孩子连接
  • 反转二叉树:我直接把左孩子存为右孩子,右孩子存为左孩子…
  • 明确给出结点编号之间的关系–>用"静态二叉树"

Code

#include<bits/stdc++.h>
using namespace std;

vector<vector<int>> order(2);

struct node{
	int data,left,right;
}nod[15];

void inorder(int root){
	if(root==-1) return;
	inorder(nod[root].left);
	order[1].push_back(nod[root].data);
	inorder(nod[root].right);
}

void level(int root){
	queue<int> q;
	q.push(root);
	while(!q.empty()){
		int no=q.front();
		q.pop();
		order[0].push_back(nod[no].data);
		if(nod[no].left!=-1) q.push(nod[no].left);
		if(nod[no].right!=-1) q.push(nod[no].right);
	}
}

int main(){
	#ifndef ONLINE_JUDGE
	freopen("data.txt","r",stdin);
	#endif
	
	int n;
	char l,r;
	cin>>n;
	getchar();  //!!!
	int root;
	bool hash[n];
	memset(hash,false,sizeof(hash));
	for(int i=0;i<n;i++){
		nod[i].data=i;
		scanf("%c %c",&l,&r);
		getchar();  //!!!
		if(l=='-') nod[i].right=-1;
		else{
			nod[i].right=l-'0';
			hash[l-'0']=true;
		}
		if(r=='-') nod[i].left=-1;
		else{
			nod[i].left=r-'0';
			hash[r-'0']=true;
		}
	}	
	for(int i=0;i<n;i++){
		if(hash[i]==false){
			root=i;
			break;
		}
	}
	inorder(root);
	level(root);
	for(int i=0;i<2;i++){
		for(int j=0;j<order[i].size();j++){
			if(j!=0) printf(" ");
			printf("%d",order[i][j]);
		}
		printf("\n");
	}
	
	return 0;	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值