通过数组和队列构造二叉树方法(用于算法测试),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());
}
相关推荐
程序猿编码1 小时前
榨干 RTX5090 算力!Qwen3 专用单卡推理引擎,手写C++/CUDA 算子实现 MTP 推测解码
开发语言·c++·大模型推理·qwen3·多模态推理
西飘客2 小时前
vs 怎么根据dll 生成lib文件
c++·qt
程序员老陆3 小时前
深入理解 C++ thread_local:线程私有存储的正确打开方式
开发语言·c++·程序设计
信奥卷王3 小时前
[GESP202609 六级] 分树规划
算法
夏幻灵3 小时前
LeetCode 21:合并两个有序链表——双指针与哑节点详解
算法·leetcode·链表
徐小黑ACG5 小时前
Golang 基础05 结构体struct
开发语言·算法·golang
码完就睡5 小时前
数据结构——红黑树
数据结构
码爸5 小时前
数据结构详细介绍
数据结构
Navigator_Z5 小时前
LeetCode //C - 1286. Iterator for Combination
c语言·算法·leetcode