Created
August 7, 2017 02:45
-
-
Save cixuuz/ce94283cac108b12166bd9ca0aec5459 to your computer and use it in GitHub Desktop.
[108. Convert Sorted Array to Binary Search Tree] #leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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) { | |
| if (nums.length == 0) return null; | |
| return helper(nums, 0, nums.length-1); | |
| } | |
| public TreeNode helper(int[] nums, int start, int end) { | |
| if (start > end) return null; | |
| int mid = (end - start) / 2 + start; | |
| TreeNode left = helper(nums, start, mid-1); | |
| TreeNode right = helper(nums, mid+1, end); | |
| TreeNode node = new TreeNode(nums[mid]); | |
| node.left = left; | |
| node.right = right; | |
| return node; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment