您的位置:首页 > 其它

[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