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

};
相关推荐
·云扬·6 小时前
【BUG】远程连接阿里云服务器上的redis报错
服务器·阿里云·bug
upp7 小时前
[bug]解决vscode+cline使用mcp服务报错spawn npx enoent spawn npx enoent
ide·vscode·bug·js
shenxiaolong_code8 小时前
编译器bug ?
c++·bug·meta programming·compiler bug
枸杞配码21 小时前
arthas线上不停机修改bug
ide·pycharm·bug
Htht1111 天前
【Github】之【Bug】一直无法连接github的ssh
ssh·github·bug
致微3 天前
Vue项目 bug 解决
前端·vue.js·bug
网安小陈3 天前
【网安】处理项目中的一些常见漏洞bug(java相关)
java·开发语言·数据库·安全·web安全·网络安全·bug
北冥有鱼被烹5 天前
【问题记录】C语言一个程序bug定位记录?(定义指针数组忘记[])
c语言·bug
越学不动啦6 天前
三、概念篇+Bug篇
bug·测试·软件测试入门·bug测试
伏游6 天前
【BUG】生产环境死锁问题定位排查解决全过程
服务器·数据库·spring boot·后端·postgresql·bug