Simple and Elegant C++ Solution 20 ms


  • 0
    B
     TreeNode* sortedArrayBSTUtil(vector<int>& nums, int low, int high){
            
        
            TreeNode* root;
            
            if(low == high){
                return NULL;
            }
            
            if(low < high){
                
                int mid = (low + high)/2;
                
                root = new TreeNode(nums[mid]);
                root->left = sortedArrayBSTUtil(nums,low,mid);
                root->right = sortedArrayBSTUtil(nums,mid+1,high);
                
            }
            
            return root;
        }
    
        TreeNode* sortedArrayToBST(vector<int>& nums) {
            
            
            if(nums.size() == 0){
                return NULL;
            }
            
            return sortedArrayBSTUtil(nums,0,nums.size());
            
        }

  • 0
    L

    Why my Java solution ran in 1ms and C++ in 20ms? Same code:

    public class Solution {
        public TreeNode sortedArrayToBST(int[] nums) {
            return sortedArrayToBST(nums, 0, nums.length - 1);
        }
        
        private TreeNode sortedArrayToBST(int[] nums, int left, int right) {
            if(left > right) return null;
            
            int mid = ((right - left) / 2) + left;
            TreeNode node = new TreeNode(nums[mid]);
            
            node.left = sortedArrayToBST(nums, left, mid - 1);
            node.right = sortedArrayToBST(nums, mid + 1, right);
            
            return node;
        }
    }

Log in to reply
 

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