BUG未解之谜01-指针引用之谜

在leetcode里面刷题出现的问题,当我在sortedArrayToBST里面给root赋予初始值NULL之后,问题得到解决!

理论上root是未初始化的变量,然后我进入insert函数之后,root引用的内容也是未知值,因此无法给原来的二叉树完成初始化!

本题解决方案要么是给root赋予NULL初始值,要么是去掉if(!root)这一行!

cpp 复制代码
class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        TreeNode* root;
        int sz=nums.size();
        insert(nums,root,0,sz-1);
        return root;
    }
    void insert(vector<int>& v,TreeNode*& root, int l,int r){
        if(l<=r){
            int mid=(l+r)/2;
            if(!root)
                root=new TreeNode(v[mid]);
            insert(v,root->left,l,mid-1);
            insert(v,root->right,mid+1,r);
        }
    }

};
相关推荐
隔窗听雨眠4 小时前
Library Cache Lock性能故障深度解析:JDBC驱动Bug、绑定变量长度与游标激增的连环效应
bug·library
盗理者6 小时前
AI Agent 工程实践|让 AI Agent 自动修 Bug:定位、修改、测试与人工审核
人工智能·bug·agent
程序员AlbertTu7 小时前
Linux 系统 Bug 调试操作手册
linux·postgresql·bug
深念Y2 天前
Opencode Event 表写入优化方案
数据库·人工智能·ai·node.js·bug·优化·opencode
姚青&3 天前
Bug基本概念
bug
AI多Agent协作实战派3 天前
AI多Agent协作系统实战(三十九):AI修对了Bug,却越了权——自动化团队的第一条铁律
人工智能·自动化·bug
深念Y5 天前
AMD 芯片组驱动触发高频 SSD 写入的问题及解决方案
windows·bug·ssd·日志·芯片·驱动·amd
加油码5 天前
探秘 volatile关键字:编译器的过度优化
linux·bug·信号处理
鹿屿二向箔5 天前
keil5.39版本使用AC6编译器不能位域操作的BUG使用STM32U385系列MCU
stm32·单片机·bug
angryshan6 天前
goLang配置断点流程
go·bug