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

};
相关推荐
l1t2 天前
修改一个触发PostgreSQL 17.2 bug的SQL
sql·postgresql·bug
包小黑2 天前
【Linux】bug登记好习惯:发现bug,用命令行截取对应日志
linux·bug
癫狂的兔子4 天前
【BUG】【Python】逆序取值为空
bug
癫狂的兔子4 天前
【BUG】【Python】精确度问题
python·bug
癫狂的兔子4 天前
【BUG】【Python】合并两个列表
bug
癫狂的兔子4 天前
【BUG】【Python】eval()报错
python·bug
余生H4 天前
Ai编程翻车修车记3 -一次因为移除监听器失败导致bug后的DOM事件深入学习
学习·bug·ai编程
癫狂的兔子4 天前
【BUG】【Python】list切片和list.reverse()的区别
bug
gladiator+5 天前
Weblog项目bug合集
bug
workflower6 天前
小强地狱(Bug Hell)
大数据·bug·团队开发·需求分析·个人开发·结对编程