PAT甲级 1099 Build A Binary Search Tree (30 分)

\quad 本题意在告诉你每个节点的左右孩子信息,需要你把树建出来,接着利用BST中序遍历值是有序的这一特性重新给每个节点赋值。最后再来个BFS对树进行层次遍历输出即可。

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

int n;
struct TreeNode
{
	int val;
	int left, right;
}treeNode[101];
int val[101];
int num = 0;

void inorder(int root)
{
	if(root==-1) return;
	inorder(treeNode[root].left);
	treeNode[root].val = val[num++];
	inorder(treeNode[root].right);
}

void bfs(int root)
{
	queue<int> q;
	q.push(root);
	num = 0;
	while(!q.empty())
	{
		int t = q.front();
		q.pop();
		cout << treeNode[t].val;
		num++;
		if(num<n) cout << " ";
		if(treeNode[t].left!=-1) q.push(treeNode[t].left);
		if(treeNode[t].right!=-1) q.push(treeNode[t].right);
	}
}

int main(int argc, char const *argv[])
{
	cin >> n;
	for (int i = 0; i < n; ++i)
	{
		int l, r;
		cin >> l >> r;
        treeNode[i].left = l;
        treeNode[i].right = r;
	}
	for (int i = 0; i < n; ++i)
	{
		cin >> val[i];
	}
	sort(val, val+n);
	inorder(0);
	bfs(0);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40438165/article/details/89855017