mardi 23 juin 2020

Convert Sorted Array to Binary Search Tree problem with finding midterm

while I was doing the question on leetcode I found that my code does not work when I use

int mid=(start+end)/2

but works for

int mid = (start+end)/2 + ((start+end)&1);

So I want to ask since my goal is to find the mid term why does it show wrong output

class Solution {
public:
    TreeNode*build(const vector<int>& nums,int start,int end){
      if(start>end){
        return NULL;
      }
      int mid=(start+end)/2+ ((start+end)&1);
      TreeNode*root=new TreeNode(nums[mid]);
      root->left=build(nums,start,mid-1);
      root->right=build(nums,mid+1,end);
      return root;
    }
    TreeNode* sortedArrayToBST(vector<int>& nums) {
      return build(nums,0,nums.size()-1);
        
    }
};

Given the sorted array: [-10,-3,0,5,9],

output: [0,-3,9,-10,null,5]

however when I use mid= (start+end)/2;

output=[0,-10,5,null,-3,null,9]

Aucun commentaire:

Enregistrer un commentaire