|
| 1 | +/* |
| 2 | + * @lc app=leetcode id=108 lang=java |
| 3 | + * |
| 4 | + * [108] Convert Sorted Array to Binary Search Tree |
| 5 | + * |
| 6 | + * https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/ |
| 7 | + * |
| 8 | + * algorithms |
| 9 | + * Easy (49.29%) |
| 10 | + * Total Accepted: 251K |
| 11 | + * Total Submissions: 501.5K |
| 12 | + * Testcase Example: '[-10,-3,0,5,9]' |
| 13 | + * |
| 14 | + * Given an array where elements are sorted in ascending order, convert it to a |
| 15 | + * height balanced BST. |
| 16 | + * |
| 17 | + * For this problem, a height-balanced binary tree is defined as a binary tree |
| 18 | + * in which the depth of the two subtrees of every node never differ by more |
| 19 | + * than 1. |
| 20 | + * |
| 21 | + * Example: |
| 22 | + * |
| 23 | + * |
| 24 | + * Given the sorted array: [-10,-3,0,5,9], |
| 25 | + * |
| 26 | + * One possible answer is: [0,-3,9,-10,null,5], which represents the following |
| 27 | + * height balanced BST: |
| 28 | + * |
| 29 | + * 0 |
| 30 | + * / \ |
| 31 | + * -3 9 |
| 32 | + * / / |
| 33 | + * -10 5 |
| 34 | + * |
| 35 | + * |
| 36 | + */ |
| 37 | +/** |
| 38 | + * Definition for a binary tree node. |
| 39 | + * public class TreeNode { |
| 40 | + * int val; |
| 41 | + * TreeNode left; |
| 42 | + * TreeNode right; |
| 43 | + * TreeNode(int x) { val = x; } |
| 44 | + * } |
| 45 | + */ |
| 46 | +class Solution { |
| 47 | + public TreeNode sortedArrayToBST(int[] nums) { |
| 48 | + return BST(nums, 0, nums.length - 1); |
| 49 | + } |
| 50 | + |
| 51 | + public TreeNode BST(int[] nums, int start, int end) { |
| 52 | + if (start > end) return null; |
| 53 | + int mid = (start + end) / 2; |
| 54 | + TreeNode root = new TreeNode(nums[mid]); |
| 55 | + root.left = BST(nums, start, mid - 1); |
| 56 | + root.right = BST(nums, mid + 1, end); |
| 57 | + return root; |
| 58 | + } |
| 59 | +} |
| 60 | + |
0 commit comments