通过数组和队列构造二叉树方法(用于算法测试),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());
}
相关推荐
裕晟资质规划8 小时前
武器装备科研生产单位保密资质申请方法论:条件模型与流程拆解
人工智能·算法
会周易的程序员9 小时前
给 PLC 写一个字节码虚拟机:STVM 虚拟机架构设计
开发语言·c++·虚拟机·软plc·iec61131·stvm
小灰灰搞电子9 小时前
完全驾驭 Qt 与数据库:C++ ORM 框架 QxOrm 原理与实践指南
数据库·c++·qt
QT界面美化性能优化9 小时前
QT+AI:使用AI技术为QT应用程序赋能
c++·人工智能·qt·opencv·qt教程·qt6.3
en.en..9 小时前
C语言 标准输入 / 输出缓冲区
算法
吃好睡好便好11 小时前
查找函数的使用
学习·算法·matlab·生活·查找函数
学习星球11 小时前
单调栈——从“找下一个更大的“到柱状图中的最大矩形
数据库·c++·算法·leetcode·xcode
小灰灰搞电子12 小时前
C++ 引用折叠详解
c++
专注仿真12 小时前
Spring AI 实现智能对话系统项目指南
数据结构·spring·机器学习
靠沿12 小时前
贪心算法专题(二)
算法·贪心算法