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

};
相关推荐
酷酷-3 小时前
彩虹易支付最新版源码及安装教程(修复BUG+新增加订单投诉功能)
html·php·bug
佛系小嘟嘟12 小时前
Android-由switch-case和view.getId()引起的bug:错误:需要常量表达式 的解决办法
android·bug
未来可期LJ12 小时前
【测试-BUG篇】软件测试的BUG知识你了解多少呢?
软件测试·bug
软件测试很重要12 小时前
追梦无Bug的软件世界
bug
我又来搬代码了1 天前
【Android】【bug】ImageView设置scaleType不生效的问题
android·bug
吴恩达亲传弟子1 天前
【Bug】解决 Ubuntu 中 “error: Unable to Find Python3 Executable” 错误
linux·ubuntu·bug
john_hjy2 天前
8. Bug 与 Error
javascript·bug
鸽芷咕3 天前
【Python报错已解决】 Encountered error while trying to install package.> lxml
开发语言·python·bug
鸽芷咕3 天前
【Python报错已解决】[notice] A new release of pip available: 22.2 -> 22.2.2
开发语言·python·bug·pip
倩倩_ICE_王王3 天前
Apache安装后无法启动的问题“不能再本地计算机启动apache”
bug·apache