BUG未解之谜01-指针引用之谜

在leetcode里面刷题出现的问题,当我在sortedArrayToBST里面给root赋予初始值NULL之后,问题得到解决!
理论上root是未初始化的变量,然后我进入insert函数之后,root引用的内容也是未知值,因此无法给原来的二叉树完成初始化!
本题解决方案要么是给root赋予NULL初始值,要么是去掉if(!root)这一行!


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

};

在这里插入图片描述

相关推荐

  1. 函数的“重载”,全人工打造

    2024-03-27 15:56:02       25 阅读
  2. 探索哥德巴赫猜想:数学的

    2024-03-27 15:56:02       56 阅读
  3. 金字塔建设

    2024-03-27 15:56:02       36 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-27 15:56:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-27 15:56:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-27 15:56:02       82 阅读
  4. Python语言-面向对象

    2024-03-27 15:56:02       91 阅读

热门阅读

  1. 一些常见的PostgreSQL问题和答案

    2024-03-27 15:56:02       38 阅读
  2. 代码随想录阅读笔记-二叉树【递归遍历】

    2024-03-27 15:56:02       40 阅读
  3. Mybatis在SpringBoot中是如何被加载执行

    2024-03-27 15:56:02       35 阅读
  4. GDAL的数据类型(9)

    2024-03-27 15:56:02       36 阅读
  5. Python中模块的定义、用法

    2024-03-27 15:56:02       41 阅读