关于一道完全二叉搜索树的题目求解
  • 板块灌水区
  • 楼主若榆若木
  • 当前回复0
  • 已保存回复0
  • 发布时间2024/11/24 18:46
  • 上次更新2024/11/24 20:33:52
查看原帖
关于一道完全二叉搜索树的题目求解
176006
若榆若木楼主2024/11/24 18:46

题目是另一个平台上的,网上推荐的是直接用数组处理,但是蒟蒻想试试用链接结构做,然后就卡死了,并且思路也有些混乱了,烦请大佬们帮忙看看

Orz

题目描述:

二叉搜索树(BST)递归定义为具有以下属性的二叉树:

节点的左子树只包含键小于节点键的节点。

节点的右子树只包含键大于或等于节点键的节点。

左右子树也必须是二叉搜索树。

完全二叉树(CBT)是完全填充的树,可能除了最后一层,从左到右填充。

现在给定一个不同的非负整数键序列,如果要求树也必须是CBT,就可以构建一个唯一的BST。你应该输出这个BST的层次遍历序列。

输入:

第一行输入一个n(n≤2000),表示将要输入的数字的个数

第二行有n个数字(不重复且无序)

输出:

n个数字,表示完全二叉搜索树的层次遍历结果

样例输入:

10

1 2 3 4 5 6 7 8 9 0

样例输出:

6 3 8 1 5 7 9 0 2 4

//我的代码
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <cmath>
using namespace std;
int n;
int a[2005];
// 定义二叉树节点结构
struct Node {
    int data;
    Node* left;
    Node* right;
    // 构造函数
    Node(int value) : data(value), left(nullptr), right(nullptr) {}
};

// 计算左子树的长度
int getLeftLength(int n) {
    int h = (int)ceil(log2(n + 1));
    int t = (int)pow(2, h) - 1;
    if (t >= n) t = (int)pow(2, h - 1);
    return t;
}

// 插入函数,插入新节点到二叉搜索树中
Node* insert(Node* root, int left, int right) {
    if (left > right) return nullptr;
    int L = getLeftLength(right - left + 1);
    int mid = left + L;
    root = new Node(a[mid]);
    root->left = insert(root->left, left, mid - 1);
    root->right = insert(root->right, mid + 1, right);
    return root;
}

void printLevelOrder(Node* root) {
    if (root == nullptr) return;
    queue<Node*> q;
    q.push(root);
    while (!q.empty()) {
        Node* node = q.front();
        q.pop();
        cout << node->data << " ";
        if (node->left != nullptr) q.push(node->left);
        if (node->right != nullptr) q.push(node->right);
    }
}

int main() {
    Node* root = nullptr;  // 初始化为空树
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    sort(a, a + n, greater<int>()); // 逆序排序
    root = insert(root, 0, n - 1);
    printLevelOrder(root);
    return 0;
}
2024/11/24 18:46
加载中...