PAT甲级1099 Build A Binary Search Tree (30分)|C++实现

一、题目描述

原题链接
在这里插入图片描述

Input Specification:

在这里插入图片描述

​​Output Specification:

For each test case, print in one line the level order traversal sequence of that tree. All the numbers must be separated by a space, with no extra space at the end of the line.

Sample Input:

9
1 6
2 3
-1 -1
-1 4
5 -1
-1 -1
7 -1
-1 8
-1 -1
73 45 11 58 82 25 67 38 42

Sample Output:

58 25 82 11 38 67 45 73 42

二、解题思路

BST的简单题,我们把每个结点设置为一个结构体,包括里面的数据,左孩子和右孩子。值得注意的是,BST的中序遍历事实上就是所有数据从小到大排序的序列,基于这个事实,我们可以用中序遍历,把所有结点的数据补充完整。之后进行层序遍历即可。

三、AC代码

#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn = 110;
int all[maxn];
int n, t = 0;
struct Node
{
    int key, lchild, rchild;
}node[maxn];
void inOrder(int root)  //中序遍历
{
    if(root == -1)  return;
    inOrder(node[root].lchild);
    node[root].key = all[t++];
    inOrder(node[root].rchild);
}
void BFS(int root)  //层序遍历
{
    queue<int> q;
    q.push(root);
    int cnt = 0;
    while(!q.empty())
    {
        int now = q.front();
        q.pop();
        cnt++;
        printf("%d", node[now].key);
        cnt == n ? printf("\n") : printf(" ");
        if(node[now].lchild != -1)   q.push(node[now].lchild);
        if(node[now].rchild != -1)   q.push(node[now].rchild);
    }
    return;
}
int main()
{
    scanf("%d", &n);
    for(int i=0; i<n; i++)
        scanf("%d%d", &node[i].lchild, &node[i].rchild);
    for(int i=0; i<n; i++)
        scanf("%d", &all[i]);
    sort(all, all+n);
    inOrder(0);
    BFS(0);
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值