通过数组和队列构造二叉树方法(用于算法测试),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());
}
相关推荐
To_OC2 小时前
LC 207 课程表:刚学图论那会儿,我连这是拓扑排序都没看出来
javascript·算法·leetcode
To_OC2 小时前
LC 208 实现 Trie 前缀树:曾被名字劝退,写完发现是送分题
javascript·算法·leetcode
BadBadBad__AK4 小时前
线段树维护区间 k 次方和
c++·数学·算法·stl
卷无止境16 小时前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
_清歌17 小时前
DSpark 深度解读:DeepSeek-V4 如何用「半自回归」把推理速度提升 85%
算法
统计实现局17 小时前
SVD 的三步走:双对角化、Givens 收敛、排序
算法
躬行见万象17 小时前
《VLA 系列》UniLab 强化训练 | G1 机器人 |复现
算法
统计实现局17 小时前
对称不定分解(Bunch-Kaufman):为什么 Cholesky 不够用
算法
统计实现局17 小时前
dqrsl 拆解:拿着 QR 结果能算出哪 5 种东西
算法