1115 Counting Nodes in a Binary Search Tree(分治建树--二叉搜索数)

PAT目前遇到的分治建树的情况:
case 1:给一个堆(HEAP),让你建树分治建树1–根据堆
case 2: 给前序加中序+前序(后序)确定一棵树分治建树2–前中后3选2
case 3:动态建立二叉排序树(BST)(本题)
注意建立二叉搜索书(BST)时,除了可以根据插入顺序也可以根据前序遍历序列,例如PAT甲级1135 1143

  • 注意点:注意参数传递是值传递,在本题中也就是地址复制过去,所以注意递归时,先开辟空间,才能链接起来
#include<bits/stdc++.h>
#include<unordered_set>
#define f(i,a,b) for(int i=a;i<=b;++i)
#define fd(i,a,b) for(int i=a;i>=b;--i)
#define debug(x) cerr<<#x<<": "<<x<<endl;
using namespace std;
typedef long long ll;
struct node {
	struct node *l;
	struct node *r;
	int w;
	node() {
		this->l = NULL;
		this->r = NULL;
		this->w = -1001;
	}
};
int a[1005];
//考察建链表树
void build(node * u,int x) {
	if (u->w== -1001) {
		u->w = x;
		return;
	}
	if (x <= u->w) {
		if (u->l == NULL)u->l = new node;
		build(u->l, x);
	}
	else {
		if (u->r == NULL)u->r = new node;
		build(u->r, x);
	}
}

//考察dfs
int num[1005];
void dfs(node * u, int x) {
	if (u == NULL)return;
	num[x]++;
	dfs(u->l, x + 1);
	dfs(u->r, x + 1);
}
int main()
{
#ifndef ONLINE_JUDGE
	freopen("in.txt", "r", stdin);
#endif
	int n;cin >> n;
	f(i, 1, n)cin >> a[i];
	node *root = new node;
	root->w = a[1];
	f(i, 2, n)build(root, a[i]);
	dfs(root, 0);
	int fg = 0, a=0, b=0;
	fd(i, 1004, 0) {
		if (!num[i])continue;
		if (fg == 0) {
			fg++;
			a = num[i];
		}
		else if (fg == 1) {
			b = num[i];
			break;
		}
	}
	cout << a << " + " << b << " = " << a + b << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值