[LeetCode] 108. Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Thought process:
Divide and conquer, recursively attach left sub-tree and right sub-tree to root:
Thought process:
Divide and conquer, recursively attach left sub-tree and right sub-tree to root:
- Base case: when the array is empty, return null.
- Recurrence: root is at array's length / 2. Left sub-tree is the root of the first half of the array. Right sub-tree is the root of the second half of the array.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode sortedArrayToBST(int[] nums) { return sortedArrayToBST(nums, 0, nums.length); } private TreeNode sortedArrayToBST(int[] nums, int start, int end) { if (start == end) { return null; } int mid = start + (end - start) / 2; TreeNode root = new TreeNode(nums[mid]); TreeNode left = sortedArrayToBST(nums, start, mid); TreeNode right = sortedArrayToBST(nums, mid + 1, end); root.left = left; root.right = right; return root; } } |
Time complexity:
Say the array contains n elements. Every element is visited exactly once. So the overall time complexity is O(n).
Comments
Post a Comment