Advertisement
Guest User

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

a guest
Aug 24th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.92 KB | None | 0 0
  1. // Problem: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
  2.  
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement