SHARE
TWEET

108. Convert Sorted Array to BST|Time: O(n) | Space:O(n)

a guest Aug 24th, 2019 70 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Problem: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
  2. // Solution: https://www.youtube.com/watch?v=PZYTs9y4f4o
  3.  
  4. /**
  5.  * Definition for a binary tree node.
  6.  * public class TreeNode {
  7.  *     int val;
  8.  *     TreeNode left;
  9.  *     TreeNode right;
  10.  *     TreeNode(int x) { val = x; }
  11.  * }
  12.  */
  13. class Solution {
  14.     public TreeNode sortedArrayToBST(int[] nums) {
  15.         if(nums == null || nums.length == 0) {
  16.             return null;
  17.         }
  18.        
  19.         return constructBSTRecursive(nums, 0, nums.length - 1);
  20.     }
  21.    
  22.     private TreeNode constructBSTRecursive(int[] nums, int left, int right) {
  23.         if(left > right) {
  24.             return null;
  25.         }
  26.        
  27.         int mid = left + (right - left) / 2;
  28.         TreeNode current = new TreeNode(nums[mid]);
  29.         current.left = constructBSTRecursive(nums, left, mid - 1);
  30.         current.right = constructBSTRecursive(nums, mid + 1, right);
  31.         return current;
  32.     }
  33. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top