1099 Build A Binary Search Tree (30 分)-PTA甲级-BST建树

本题与1064一模一样的思路,建树时统计当前节点左子树的节点数量,以此确定当前节点的num值。

#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
typedef long long ll;
const int maxn = 1e2+5,inf=1e9;
struct node
{
	int num;
	node *left=nullptr, *right=nullptr;
};
int n,r[maxn];
vector<pair<int, int>> T;
int count_node(int now)
{
	if (now == -1)
		return 0;
	else
		return count_node(T[now].first) + count_node(T[now].second) + 1;
}
node* creat_tree(int low, int high, int now)
{
	if (now == -1)
		return nullptr;
	int left_num = count_node(T[now].first);
	node *t = new node();
	t->num = r[low + left_num];
	t->left = creat_tree(low, low + left_num - 1, T[now].first);
	t->right = creat_tree(low + left_num + 1, high, T[now].second);
	return t;
}
void BFS(node *t)
{
	queue<node *> q;
	q.push(t);
	while (!q.empty())
	{
		auto top = q.front();
		q.pop();
		cout << top->num;
		if (--n)
			cout << " ";
		if (top->left != nullptr)
			q.push(top->left);
		if (top->right != nullptr)
			q.push(top->right);
	}
}
int main()
{	
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		int a, b;
		cin >> a >> b;
		T.push_back(make_pair(a, b));
	}
	for (int i = 0; i < n; i++)
		cin >> r[i];
	sort(r, r + n);
	node *t = creat_tree(0, n - 1, 0);
	BFS(t);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值