What is the difference between these two codes?

  • 0

    Here is the ac code:

    class Solution {
        TreeNode* fineNodes(vector<int>& nums, int leftInd, int rightInd)
             if (leftInd > rightInd) return NULL;
             int mid = (leftInd + rightInd) >> 1;
             TreeNode *node = new TreeNode(nums[mid]);
             node->right = fineNodes(nums, mid + 1, rightInd);
             node->left = fineNodes(nums, leftInd, mid - 1);
             return node;
    TreeNode* sortedArrayToBST(vector<int>& nums) {
             return fineNodes(nums, 0, nums.size() - 1);

    However, if I declare the variable "node" in the fineNodes function like this:

    TreeNode node(nums[mid]);

    and at the end of this funtion:

    return &node;

    then LeetCode will tell me Runtime Error. But I tested this code in my ide, this code still work without Runtime Error given the same input.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.