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);
        }
    }

};
相关推荐
阿部多瑞 ABU1 天前
《智能学号抽取系统》V5.9.5 发布:精简代码,修复移动端文件读取核心 Bug
vue·html·bug
qq_452396232 天前
【工程实战】第八篇:报告美学 —— Allure 深度定制:让 Bug 定位精准到秒
开发语言·python·bug
tkokof13 天前
捉虫(Bug)小记
人工智能·深度学习·bug·游戏开发
南宫萧幕3 天前
基于上一篇文章VMware+openweb UI+ollama+docker的bug问题总结
docker·容器·bug·openweb ui
呼啦啦5613 天前
测试(BUG篇)
bug
ZC跨境爬虫3 天前
3D地球卫星轨道可视化平台开发Day2(轨道错位Bug修复+模块化结构优化)
前端·3d·html·json·bug
柠檬07113 天前
记录bug :C++调用python 路径问题
c++·python·bug
初圣魔门首席弟子5 天前
bug20260415
c++·bug
万粉变现经纪人5 天前
如何解决 pip install flash-attention 报错 需要 SM_80+(Ampere)架构 问题
python·架构·django·bug·virtualenv·pip·pygame
zhanglianzhao6 天前
Gazebo仿真机器人和相机时Gazebo ROS Control 插件偶发性加载失败bug分析
机器人·bug·ros·gazebo·ros_control