【2019暑期】【PAT甲级】1115 Counting Nodes in a BST (30 分)

48 篇文章 0 订阅

自己用数组写,25分,后面的有一个答案错误和段错误,所有的题解都是用指针写的,不知道自己该怎么改
到时候学一下指针的写法吧
暂存

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

int n; 
int maxlevel = -1;
int tree[10000],num[10000];

void dfs(int root,int level){
	if(tree[root*2+1]==9999&&tree[root*2+2]==9999){
		maxlevel = max(maxlevel,level);
		return ;
	}
	//if(level>maxlevel) maxlevel = level;
	if(tree[root*2+1]!=9999){
		num[level]++;
		dfs(root*2+1,level+1);		
	} 
	if(tree[root*2+2]!=9999){
		num[level]++;
		dfs(root*2+2,level+1);
	} 
}

int main()
{
 	cin >> n;
 	//memset(tree,9999,sizeof(tree));
 	for(int i=0; i<10000; i++) tree[i] = 9999;
 	cin >> tree[0];
 	for(int i=1; i<n; i++){
 		int a;
 		cin >> a;
 		int k = 0;
 		//cout << tree[k] << endl;
        while(tree[k] != 9999){
        	//cout << tree[k] << " " << k << " k ";
			//cout <<tree[k*2+1] << " " << a << endl;
        	if(a<=tree[k]&&tree[k*2+1]==9999){
        		tree[k*2+1] = a;
        		break;
			}
			if(a<=tree[k]&&tree[k*2+1]!=9999){
				k = k*2+1;
				continue;
			} 
			if(a>tree[k]&&tree[k*2+2]==9999){
				tree[k*2+2] = a;
				break;
			}
			if(a>tree[k]&&tree[k*2+2]!=9999){
				k = k*2+2;
				continue;
			}
		} 		
 		//cout << endl;
	 }
 	//for(int i=0; i<n*2; i++) cout << tree[i] <<" ";
 	dfs(0,1);
 	cout << num[maxlevel-1]<<" + " <<num[maxlevel-2];
	cout << " = " <<num[maxlevel-1]+num[maxlevel-2]<< endl;
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值