1064 Complete Binary Search Tree (30 分)——甲级(完全二叉搜索树)

本文介绍了一种特殊二叉搜索树——完全二叉搜索树的构造方法及其实现过程,通过将给定的序列排序后,利用完全二叉树的性质构建唯一树,并实现了层序遍历输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:
在这里插入图片描述
A Complete Binary Tree (CBT) is a tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right.

Now given a sequence of distinct non-negative integer keys, a unique BST can be constructed if it is required that the tree must also be a CBT. You are supposed to output the level order traversal sequence of this BST.

Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤1000). Then N distinct non-negative integer keys are given in the next line. All the numbers in a line are separated by a space and are no greater than 2000.

Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding complete binary search tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.

Sample Input:
10
1 2 3 4 5 6 7 8 9 0
Sample Output:
6 3 8 1 5 7 9 0 2 4

题目大意:给出二叉搜索树的一个序列,如果这棵树还要求是完全二叉树的话,这棵树就是唯一的。现在要输出这棵树的层序遍历。
思路:要用到二叉搜索树、完全二叉树两种树的特性:

  1. 二叉搜索树:键值从小到大排为中序遍历
  2. 完全二叉树:若用从1开始的数组存,对于一个索引为index的结点来说,index2为其左儿子,index2+1为其右二子。

根据这两点,先将序列从小到大排序,然后在数组中按照中序遍历建树,最后BFS。

代码如下:

#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
typedef struct node* bst;
int sum = 1;//现在是数组中第几个数被插入树中
struct node
{
    int data;
    bst left;
    bst right;
};
bst build(int a[], int index, int n)
{
    if(index > n) return NULL;
    bst t = new node;
    t->left = build(a, index*2, n);
    t->data = a[sum++];
    t->right = build(a, index*2+1, n);
    return t;
}
void bfs(bst t, int n)
{
    queue<bst>q;
    q.push(t);
    int cnt = 0;
    while(!q.empty())
    {
        bst x = q.front();
        cnt ++;
        if(cnt == n) cout << x->data;
        else cout << x->data << " ";
        if(x->left) q.push(x->left);
        if(x->right) q.push(x->right);
        q.pop();
    }
    cout << endl;
}
int main()
{
    int n, a[1001];
    cin >> n;
    int i;
    for(i=1; i<=n; i++) cin >> a[i];
    sort(a+1, a+1+n);
    bst t = build(a, 1, n);
    bfs(t, n);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值