LeetCode 108. Convert Sorted Array to Binary Search Tree
原题链接在这里:https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
题目:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
题解:
本题与Convert Sorted List to Binary Search Tree相似. 为了方便记左右index来做递归,建一个有多个argument的函数。这也是array递归的通用方法。然后中点取值返回TreeNode, 左侧用作生成left subtree, 右侧用作生成right subtree.
Time Complexity: O(n), 以为每个点只访问了一次. Space: O(logn), 递归用了O(logn)层stack.
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public TreeNode sortedArrayToBST(int[] nums) { 12 if(nums == null || nums.length == 0){ 13 return null; 14 } 15 16 return transform(nums, 0, nums.length-1); 17 } 18 19 private TreeNode transform(int [] nums, int left, int right){ 20 if(left > right){ 21 return null; 22 } 23 24 int mid = left + (right-left)/2; 25 TreeNode root = new TreeNode(nums[mid]); 26 root.left = transform(nums, left, mid-1); 27 root.right = transform(nums, mid+1, right); 28 29 return root; 30 } 31 }
类似Convert Sorted List to Binary Search Tree, Balance a Binary Search Tree.