[LeetCode]108. Convert Sorted Array to Binary Search Tree
2016-03-08 18:36
495 查看
Problem Description
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.[]https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/]
思路
二分!!!就酱!!Code
package q108; import TreeNode.*; public class Solution { public TreeNode sortedArrayToBST(int[] nums) { if (nums.length < 1) return null; TreeNode root = helper(nums, 0, nums.length - 1); return root; } public TreeNode helper(int[] nums, int i, int j) { if (i > j) return null; int mid = (i + j) / 2; TreeNode root = new TreeNode(nums[mid]); root.right = helper(nums, i, mid - 1); root.left = helper(nums, mid + 1, j); return root; } // // public static void main(String[] args) { // int[] a = { 1, 2 }; // Solution s = new Solution(); // TreeNode root = s.sortedArrayToBST(a); // Codec c = new Codec(); // System.out.print(c.serialize(root)); // } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解