文章

74

粉丝

0

获赞

94

访问

8.2k

头像
层次遍历 (创建BST优化)题解:
P1924 复旦大学2023年机试题
发布于2025年8月23日 16:59
阅读数 50

#include<iostream>
#include<cstdlib>
#include<queue>
#include<climits> // 用于INT_MAX
using namespace std;

typedef struct node{
    int data;
    struct node *lchild, *rchild;
}*BitTree;

// 利用先序遍历特性构建BST,避免低效的插入操作
BitTree create(const int* pre, int& idx, int n, int max_val) {
    if (idx >= n || pre[idx] > max_val) return nullptr;
    
    BitTree root = new node;
    root->data = pre[idx++];
    root->lchild = root->rchild = nullptr;
    
    // 左子树的最大值是当前节点值
    root->lchild = create(pre, idx, n, root->data);
    // 右子树的最大值继承自父节点的限制
    root->rchild = create(pre, idx, n, max_val);
    
    return root;
}

void Print(BitTree T){
    if(T == NULL) return;
    queue<BitTree> q;
    q.push(T);

    while(!q.empty()){
        BitTree now = q.front();
        q.pop();

        cout << now->data << ' ';
        if(now->lchild != NULL) q.push(now->lchild);
        if(now-...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发