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

};
相关推荐
残花月伴5 小时前
天机学堂——day1(修改bug)
servlet·bug
std8602113 小时前
微软 Win11 经典版 Outlook 曝 BUG,加速 SSD 损耗
microsoft·bug·outlook
花花鱼15 小时前
android 网络访问拦截器使用后的bug处理
bug
JH307321 小时前
MyBatis多表联查返回List仅一条数据?主键冲突BUG排查与解决
bug·mybatis
约翰先森不喝酒1 天前
Android BUG 之 资源文件报红但不影响运行
bug
百花~1 天前
认识BUG~
bug
ZHE|张恒2 天前
RDP 远程桌面连接:浏览器无法获取摄像头
bug
chde2Wang2 天前
Linux中bash: ls: 未找到命令… 相似命令是: ‘lz‘
linux·运维·bug·bash
阿里巴巴淘系技术团队官网博客2 天前
让AI打出丝滑连招:编码-部署-自测-改bug
人工智能·bug
lsswear2 天前
colinmollenhour/credis 1.17 bug
bug