【2019暑期】【PAT甲级】1102 Invert a Binary Tree (25 分)

本文分享了一次使用树状数据结构解决编程问题的经历,作者首次独立完成树的编写,回顾了memset函数的用法,并分享了实现过程及部分代码细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

又是一个20分,不知道那5分错在哪
第一次完全自己写树,还是很欣慰的
复习memset(a,0,sizeof(a))

#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <string>
#include <cctype>
#include <vector>
#include <cmath>
#include <map> 
#include <set>
#include <unordered_map> 
#include <cstring>
using namespace std;

int n;
struct node{
	int left,right;
};
int arr[11];
int tree[100];
vector<node> cnt;
vector<int> ans;

void over(int k){
	if(tree[k]==-1) return ;
	over(k*2+1);
	ans.push_back(tree[k]);
	over(k*2+2);
	
}

int main(){
	
    cin >> n;
	cnt.resize(n);
	memset(tree,-1,sizeof(tree));	
	for(int i=0; i<n; i++){
		char a,b;
		int aa,bb;
		cin >> a >> b;
		if(a<='9'&&a>='0') aa = (int)(a - '0');
		else aa = -1;
		if(b<='9'&&b>='0') bb = (int)(b - '0');
		else bb = -1;
		cnt[i].left = aa;
		cnt[i].right = bb;
		arr[aa] = 1;
		arr[bb] = 1;
	}
	for(int i=0; i<n; i++){
		if(arr[i]==0){
			tree[0] = i;
		}
	}
	for(int i=0; i<n; i++){
		if(cnt[tree[i]].right!=-1&&tree[i]!=-1) tree[i*2+1] = cnt[tree[i]].right;
		if(cnt[tree[i]].left!=-1&&tree[i]!=-1) tree[i*2+2] = cnt[tree[i]].left;
	}
	for(int i=0; i<100; i++){
		if(tree[i]!=-1){			
			if(i==0) cout << tree[i] ;
			else cout << " " << tree[i];
		}
	}
	cout << endl;
	over(0);
	for(int i=0; i<n; i++){					
			if(i==0) cout << ans[i] ;
			else cout << " " << ans[i];
		
	}	
	return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值