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

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

  1. Given the sorted array: [-10,-3,0,5,9],
  2.  
  3. One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
  4.  
  5. 0
  6. / \
  7. -3 9
  8. / /
  9. -10 5 

给定一个升序排序的数组,把它转成一个高度平衡的二叉搜索树(两个子树的深度相差不大于1)。

二叉搜索树的特点:

1. 若任意节点的左子树不空,则左子树上所有节点的值均小于它的根节点的值;
2. 若任意节点的右子树不空,则右子树上所有节点的值均大于它的根节点的值;
3. 任意节点的左、右子树也分别为二叉查找树;
4. 没有键值相等的节点。

中序遍历二叉查找树可得到一个关键字的有序序列,一个无序序列可以通过构造一棵二叉查找树变成一个有序序列,构造树的过程即为对无序序列进行查找的过程。

反过来,根节点就是有序数组的中间点,从中间点分开为左右两个有序数组,再分别找出两个数组的中间点作为左右两个子节点,就是二分查找法。

解法1:二分法BS + 递归Recursive

解法2: 二分法 + 迭代

Java: Recursive

  1. public TreeNode sortedArrayToBST(int[] num) {
  2. if (num.length == 0) {
  3. return null;
  4. }
  5. TreeNode head = helper(num, 0, num.length - 1);
  6. return head;
  7. }
  8.  
  9. public TreeNode helper(int[] num, int low, int high) {
  10. if (low > high) { // Done
  11. return null;
  12. }
  13. int mid = (low + high) / 2;
  14. TreeNode node = new TreeNode(num[mid]);
  15. node.left = helper(num, low, mid - 1);
  16. node.right = helper(num, mid + 1, high);
  17. return node;
  18. }

Java: Iterative  

  1. public class Solution {
  2.  
  3. public TreeNode sortedArrayToBST(int[] nums) {
  4.  
  5. int len = nums.length;
  6. if ( len == 0 ) { return null; }
  7.  
  8. // 0 as a placeholder
  9. TreeNode head = new TreeNode(0);
  10.  
  11. Deque<TreeNode> nodeStack = new LinkedList<TreeNode>() {{ push(head); }};
  12. Deque<Integer> leftIndexStack = new LinkedList<Integer>() {{ push(0); }};
  13. Deque<Integer> rightIndexStack = new LinkedList<Integer>() {{ push(len-1); }};
  14.  
  15. while ( !nodeStack.isEmpty() ) {
  16. TreeNode currNode = nodeStack.pop();
  17. int left = leftIndexStack.pop();
  18. int right = rightIndexStack.pop();
  19. int mid = left + (right-left)/2; // avoid overflow
  20. currNode.val = nums[mid];
  21. if ( left <= mid-1 ) {
  22. currNode.left = new TreeNode(0);
  23. nodeStack.push(currNode.left);
  24. leftIndexStack.push(left);
  25. rightIndexStack.push(mid-1);
  26. }
  27. if ( mid+1 <= right ) {
  28. currNode.right = new TreeNode(0);
  29. nodeStack.push(currNode.right);
  30. leftIndexStack.push(mid+1);
  31. rightIndexStack.push(right);
  32. }
  33. }
  34. return head;
  35. }
  36.  
  37. }  

Python:

  1. class Solution(object):
  2. def sortedArrayToBST(self, nums):
  3. """
  4. :type nums: List[int]
  5. :rtype: TreeNode
  6. """
  7. return self.sortedArrayToBSTRecu(nums, 0, len(nums))
  8.  
  9. def sortedArrayToBSTRecu(self, nums, start, end):
  10. if start == end:
  11. return None
  12. mid = start + self.perfect_tree_pivot(end - start)
  13. node = TreeNode(nums[mid])
  14. node.left = self.sortedArrayToBSTRecu(nums, start, mid)
  15. node.right = self.sortedArrayToBSTRecu(nums, mid + 1, end)
  16. return node
  17.  
  18. def perfect_tree_pivot(self, n):
  19. """
  20. Find the point to partition n keys for a perfect binary search tree
  21. """
  22. x = 1
  23. # find a power of 2 <= n//2
  24. # while x <= n//2: # this loop could probably be written more elegantly :)
  25. # x *= 2
  26. x = 1 << (n.bit_length() - 1) # use the left bit shift, same as multiplying x by 2**n-1
  27.  
  28. if x // 2 - 1 <= (n - x):
  29. return x - 1 # case 1: the left subtree of the root is perfect and the right subtree has less nodes
  30. else:
  31. return n - x // 2 # case 2 == n - (x//2 - 1) - 1 : the left subtree of the root
  32. # has more nodes and the right subtree is perfect.

C++:

  1. class Solution {
  2. public:
  3. TreeNode* sortedArrayToBST(vector<int>& nums) {
  4. return sortedArrayToBSTHelper(nums, 0, nums.size() - 1);
  5. }
  6.  
  7. private:
  8. TreeNode *sortedArrayToBSTHelper(vector<int> &nums, int start, int end) {
  9. if (start <= end) {
  10. TreeNode *node = new TreeNode(nums[start + (end - start) / 2]);
  11. node->left = sortedArrayToBSTHelper(nums, start, start + (end - start) / 2 - 1);
  12. node->right = sortedArrayToBSTHelper(nums, start + (end - start) / 2 + 1, end);
  13. return node;
  14. }
  15. return nullptr;
  16. }
  17. };  

C++:

  1. /**
  2. * Definition for binary tree
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. TreeNode *sortedArrayToBST(vector<int> &num) {
  13. return sortedArrayToBST(num, 0 , num.size() - 1);
  14. }
  15. TreeNode *sortedArrayToBST(vector<int> &num, int left, int right) {
  16. if (left > right) return NULL;
  17. int mid = (left + right) / 2;
  18. TreeNode *cur = new TreeNode(num[mid]);
  19. cur->left = sortedArrayToBST(num, left, mid - 1);
  20. cur->right = sortedArrayToBST(num, mid + 1, right);
  21. return cur;
  22. }
  23. };

  

类似题目:

[LeetCode] 109. Convert Sorted List to Binary Search Tree 把有序链表转成二叉搜索树

All LeetCode Questions List 题目汇总

[LeetCode] 108. Convert Sorted Array to Binary Search Tree 把有序数组转成二叉搜索树的更多相关文章

  1. LeetCode 108. Convert Sorted Array to Binary Search Tree (有序数组转化为二叉搜索树)

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

  2. [LeetCode] 109. Convert Sorted List to Binary Search Tree 把有序链表转成二叉搜索树

    Given a singly linked list where elements are sorted in ascending order, convert it to a height bala ...

  3. 108 Convert Sorted Array to Binary Search Tree 将有序数组转换为二叉搜索树

    将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树.此题中,一个高度平衡二叉树是指一个二叉树每个节点的左右两个子树的高度差的绝对值不超过1.示例:给定有序数组: [-10,-3,0,5,9], ...

  4. 37. leetcode 108. Convert Sorted Array to Binary Search Tree

    108. Convert Sorted Array to Binary Search Tree 思路:利用一个有序数组构建一个平衡二叉排序树.直接递归构建,取中间的元素为根节点,然后分别构建左子树和右 ...

  5. [LeetCode] 108. Convert Sorted Array to Binary Search Tree ☆(升序数组转换成一个平衡二叉树)

    108. Convert Sorted Array to Binary Search Tree 描述 Given an array where elements are sorted in ascen ...

  6. LeetCode 108. Convert Sorted Array to Binary Search Tree (将有序数组转换成BST)

    108. Convert Sorted Array to Binary Search Tree Given an array where elements are sorted in ascendin ...

  7. leetcode 108. Convert Sorted Array to Binary Search Tree 、109. Convert Sorted List to Binary Search Tree

    108. Convert Sorted Array to Binary Search Tree 这个题使用二分查找,主要要注意边界条件. 如果left > right,就返回NULL.每次更新的 ...

  8. [LeetCode] Convert Sorted Array to Binary Search Tree 将有序数组转为二叉搜索树

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

  9. Java for LeetCode 108 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. Javascript技能

    Javascript技能 说一说我对 Javascript 这门语言的一些总结(适合前端和后端研发) 基本认识 一些心得 思维脑图的链接(icloud 分享): https://www.icloud. ...

  2. 微信小程序~TabBar底部导航切换栏

    底部导航栏这个功能是非常常见的一个功能,基本上一个完成的app,都会存在一个导航栏,那么微信小程序的导航栏该怎么实现呢?经过无数的踩坑,终于实现了,好了,先看看效果图. 对于底部导航栏,小程序上给出的 ...

  3. php数组打乱顺序

    shuffle() PHP shuffle() 函数随机排列数组单元的顺序(将数组打乱).本函数为数组中的单元赋予新的键名,这将删除原有的键名而不仅是重新排序. 语法: bool shuffle ( ...

  4. MERGE引擎 分表后 快速查询所有数据

    MERGE存储引擎把一组MyISAM数据表当做一个逻辑单元来对待,让我们可以同时对他们进行查询.构成一个MERGE数据表结构的各成员MyISAM数据表必须具有完全一样的结构.每一个成员数据表的数据列必 ...

  5. 使用Apache commons-maths3-3.6.1.jar包,在hive上执行获取最大值的操作

    udf是对hive上的每行(单行)数据操作,现在我要实现对hive上的一列数据操作,udf函数已经满足不了我的要求了,使用udaf对hive的一列求最大值: 代码如下: package com; im ...

  6. c#语言学习笔记(1)

    环境:VS Express 2013 for Desktop 也可以vs社区版,不过学习的话,Express本版做一些小的上位机工具应该是够用了 学习的网站:https://www.runoob.co ...

  7. Java中多态

    多态:把子类看成是父类,把实现类看成是接口,这样类就具有多种形态,称为多态. 在多态中访问成员变量,访问的是父类中的成员变量. 在多态中访问成员方法,先访问的是子类,看看子类有没有覆盖重写要访问的父类 ...

  8. area标签的使用,图片中某一个部分可以点击跳转,太阳系中点击某个行星查看具体信息

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  9. zzulioj - 2619: 小新的信息统计

    题目链接:http://acm.zzuli.edu.cn/problem.php?id=2619 题目描述        马上就要新生赛了,QQ群里正在统计所有人的信息,每个人需要从群里下载文件,然后 ...

  10. Tomcat配置二级域名的分配与访问

    回顾tomcat Tomcat是Apache软件基金会(Apache Software Foundation)的一个顶级项目,由Apache, Sun和其他一些公司及个人共同开发,是目前比较流行的We ...