Convert Sorted Array to Binary Search Tree

描述

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

分析

二分法。

代码

  1. // Convert Sorted Array to Binary Search Tree
  2. // 二分法,时间复杂度O(n),空间复杂度O(logn)
  3. public class Solution {
  4. public TreeNode sortedArrayToBST (int[] nums) {
  5. return sortedArrayToBST(nums, 0, nums.length);
  6. }
  7. private static TreeNode sortedArrayToBST (int[] nums, int begin, int end) {
  8. int length = end - begin;
  9. if (length < 1) return null; // 终止条件
  10. // 三方合并
  11. int mid = begin + length / 2;
  12. TreeNode root = new TreeNode (nums[mid]);
  13. root.left = sortedArrayToBST(nums, begin, mid);
  14. root.right = sortedArrayToBST(nums, mid + 1, end);
  15. return root;
  16. }
  17. }

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/binary-tree/bst/convert-sorted-array-to-binary-search-tree.html