通过数组和队列构造二叉树方法(用于算法测试),C++ vector不能直接使用null

cpp 复制代码
#include<iostream>
#include<vector>
#include<stack>
#include<queue>
using namespace std;


struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

// 通过数组构造二叉树
TreeNode* buildTreeFromLevelOrder(const vector<int>& nodes) {
    if (nodes.empty() || nodes[0] == INT_MIN) {
        return nullptr;
    }

    TreeNode* root = new TreeNode(nodes[0]);
    queue<TreeNode*> q;
    q.push(root);

    int i = 1;
    while (!q.empty() && i < nodes.size()) {
        TreeNode* curr = q.front();
        q.pop();

        // 处理左子节点
        if (i < nodes.size() && nodes[i] != INT_MIN) {
            curr->left = new TreeNode(nodes[i]);
            q.push(curr->left);
        }
        i++;

        // 处理右子节点
        if (i < nodes.size() && nodes[i] != INT_MIN) {
            curr->right = new TreeNode(nodes[i]);
            q.push(curr->right);
        }
        i++;
    }

    return root;
}

C++ 不能直接使用null

在 C++ 中:

null 不是 C++ 的关键字

过去 C 语言NULL 被定义为 0 或 (void*)0

C++11 引入了 nullptr,这才是真正的空指针常量

即使用 NULL 或 nullptr,也不能放进 vector,因为:

vector<int> 只能存储 int 类型的值

NULL/nullptr指针类型,不能隐式转换为 int(现代 C++ 编译器会报错)

二、为什么其他语言可以?

Java

ArrayList<Integer> 可以存 null

Integer 是对象类型,null 是对象空引用

Python

10, None, 5 可以

列表可以存任意对象None空对象

JavaScript

10, null, 5 可以

数组可以存混合类型

C++

vector 不能存 null

int基本类型,不是对象没有"空"的概念

C++ 中的替代方案

方案1:用特殊值(最常用)

cpp 复制代码
const int NULL_VAL = INT_MIN;  // 或者 -1e9
vector<int> nodes = {10, 5, -3, 3, 2, NULL_VAL, 
11, 3, -2, NULL_VAL, 1};

if (nodes[i] != NULL_VAL) {
    // 不是空节点
}

方案2:用 vector<int*>(存指针)

cpp 复制代码
在这里插入代码片vector<int*> nodes = {
    new int(10), new int(5), new int(-3), 
    new int(3), new int(2), nullptr,      // 可以存 nullptr
    new int(11), new int(3), new int(-2), 
    nullptr, new int(1)
};

if (nodes[i] != nullptr) {
    curr->left = new TreeNode(*nodes[i]);
}

方案3:用 vector<optional>(C++17)

cpp 复制代码
#include <optional>

vector<optional<int>> nodes = {
    10, 5, -3, 3, 2, nullopt, 11, 3, -2, nullopt, 1
};

if (nodes[i].has_value()) {
    curr->left = new TreeNode(nodes[i].value());
}
相关推荐
有点。12 小时前
C++03阶段练习(练习题)
数据结构·算法·图论
周末也要写八哥13 小时前
经典算法实例:游戏中弱角色的数量(二)
算法
是Yu欸13 小时前
鸿蒙PC移植:2048 从网页小游戏到 AI 桌面应用
大数据·人工智能·算法·数据挖掘·openharmony·codex
鹿角片ljp13 小时前
KV Cache 解析
java·算法
liliangcsdn14 小时前
IVOL与偏度因子的对比测量分析
算法
qq_1998868714 小时前
第6板块·第4节:构建系统与多文件项目
c++·人工智能·gpu算力
threerocks15 小时前
Jev 入门第一课
算法
汉克老师16 小时前
GESP2026年9月认证C++三级( 第三部分编程题(2、分割字符串))精讲
c++·gesp·小学生·学c++编程
估值探索者16 小时前
【Python量化系统工程化 #08】关了 SSH 就停?systemd 让脚本开机自启 + 异常自动拉起
java·c++·人工智能·分类·数据挖掘
西柚研究生12345616 小时前
论文分析17:YOLOv11_UAVNet:无人机航拍图像专用目标检测算法
人工智能·python·深度学习·算法·目标检测