[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.
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:
Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
给定一个升序排序的数组,把它转成一个高度平衡的二叉搜索树(两个子树的深度相差不大于1)。
二叉搜索树的特点:
1. 若任意节点的左子树不空,则左子树上所有节点的值均小于它的根节点的值;
2. 若任意节点的右子树不空,则右子树上所有节点的值均大于它的根节点的值;
3. 任意节点的左、右子树也分别为二叉查找树;
4. 没有键值相等的节点。
中序遍历二叉查找树可得到一个关键字的有序序列,一个无序序列可以通过构造一棵二叉查找树变成一个有序序列,构造树的过程即为对无序序列进行查找的过程。
反过来,根节点就是有序数组的中间点,从中间点分开为左右两个有序数组,再分别找出两个数组的中间点作为左右两个子节点,就是二分查找法。
解法1:二分法BS + 递归Recursive
解法2: 二分法 + 迭代
Java: Recursive
public TreeNode sortedArrayToBST(int[] num) {
if (num.length == 0) {
return null;
}
TreeNode head = helper(num, 0, num.length - 1);
return head;
}
public TreeNode helper(int[] num, int low, int high) {
if (low > high) { // Done
return null;
}
int mid = (low + high) / 2;
TreeNode node = new TreeNode(num[mid]);
node.left = helper(num, low, mid - 1);
node.right = helper(num, mid + 1, high);
return node;
}
Java: Iterative
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
int len = nums.length;
if ( len == 0 ) { return null; }
// 0 as a placeholder
TreeNode head = new TreeNode(0);
Deque<TreeNode> nodeStack = new LinkedList<TreeNode>() {{ push(head); }};
Deque<Integer> leftIndexStack = new LinkedList<Integer>() {{ push(0); }};
Deque<Integer> rightIndexStack = new LinkedList<Integer>() {{ push(len-1); }};
while ( !nodeStack.isEmpty() ) {
TreeNode currNode = nodeStack.pop();
int left = leftIndexStack.pop();
int right = rightIndexStack.pop();
int mid = left + (right-left)/2; // avoid overflow
currNode.val = nums[mid];
if ( left <= mid-1 ) {
currNode.left = new TreeNode(0);
nodeStack.push(currNode.left);
leftIndexStack.push(left);
rightIndexStack.push(mid-1);
}
if ( mid+1 <= right ) {
currNode.right = new TreeNode(0);
nodeStack.push(currNode.right);
leftIndexStack.push(mid+1);
rightIndexStack.push(right);
}
}
return head;
}
}
Python:
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
return self.sortedArrayToBSTRecu(nums, 0, len(nums)) def sortedArrayToBSTRecu(self, nums, start, end):
if start == end:
return None
mid = start + self.perfect_tree_pivot(end - start)
node = TreeNode(nums[mid])
node.left = self.sortedArrayToBSTRecu(nums, start, mid)
node.right = self.sortedArrayToBSTRecu(nums, mid + 1, end)
return node def perfect_tree_pivot(self, n):
"""
Find the point to partition n keys for a perfect binary search tree
"""
x = 1
# find a power of 2 <= n//2
# while x <= n//2: # this loop could probably be written more elegantly :)
# x *= 2
x = 1 << (n.bit_length() - 1) # use the left bit shift, same as multiplying x by 2**n-1 if x // 2 - 1 <= (n - x):
return x - 1 # case 1: the left subtree of the root is perfect and the right subtree has less nodes
else:
return n - x // 2 # case 2 == n - (x//2 - 1) - 1 : the left subtree of the root
# has more nodes and the right subtree is perfect.
C++:
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return sortedArrayToBSTHelper(nums, 0, nums.size() - 1);
}
private:
TreeNode *sortedArrayToBSTHelper(vector<int> &nums, int start, int end) {
if (start <= end) {
TreeNode *node = new TreeNode(nums[start + (end - start) / 2]);
node->left = sortedArrayToBSTHelper(nums, start, start + (end - start) / 2 - 1);
node->right = sortedArrayToBSTHelper(nums, start + (end - start) / 2 + 1, end);
return node;
}
return nullptr;
}
};
C++:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *sortedArrayToBST(vector<int> &num) {
return sortedArrayToBST(num, 0 , num.size() - 1);
}
TreeNode *sortedArrayToBST(vector<int> &num, int left, int right) {
if (left > right) return NULL;
int mid = (left + right) / 2;
TreeNode *cur = new TreeNode(num[mid]);
cur->left = sortedArrayToBST(num, left, mid - 1);
cur->right = sortedArrayToBST(num, mid + 1, right);
return cur;
}
};
类似题目:
[LeetCode] 109. Convert Sorted List to Binary Search Tree 把有序链表转成二叉搜索树
All LeetCode Questions List 题目汇总
[LeetCode] 108. Convert Sorted Array to Binary Search Tree 把有序数组转成二叉搜索树的更多相关文章
- 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. 题目 ...
- [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 ...
- 108 Convert Sorted Array to Binary Search Tree 将有序数组转换为二叉搜索树
将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树.此题中,一个高度平衡二叉树是指一个二叉树每个节点的左右两个子树的高度差的绝对值不超过1.示例:给定有序数组: [-10,-3,0,5,9], ...
- 37. leetcode 108. Convert Sorted Array to Binary Search Tree
108. Convert Sorted Array to Binary Search Tree 思路:利用一个有序数组构建一个平衡二叉排序树.直接递归构建,取中间的元素为根节点,然后分别构建左子树和右 ...
- [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 ...
- 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 ...
- 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.每次更新的 ...
- [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. 这道 ...
- 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. 解题 ...
随机推荐
- 洛谷 P1816 忠诚题解
题目描述 老管家是一个聪明能干的人.他为财主工作了整整10年,财主为了让自已账目更加清楚.要求管家每天记k次账,由于管家聪明能干,因而管家总是让财主十分满意.但是由于一些人的挑拨,财主还是对管家产生了 ...
- 洛谷P4213(杜教筛)
#include <bits/stdc++.h> using namespace std; typedef long long LL; const int maxn = 3e6 + 3; ...
- Linux UART介绍
1. UART介绍 UART是一类tty设备, 是一种串行端口终端, 具体可参考<UART接口介绍>在Linux中UART属于tty驱动的一部分, 具体实现包括驱动抽象层和硬件实现层 本文 ...
- jenkins生成的HTML报告中expand与collapse问题
1.打开jenkins中脚本命令执行页面 2.在脚本命令页面的,输入框中粘贴 System.setProperty("hudson.model.DirectoryBrowserSupport ...
- 《基于WEB的独立学院补考重修管理系统研究》论文笔记(二十)
<基于WEB的独立学院补考重修管理系统研究>论文笔记(1) 一.基本信息 标题:基于WEB的独立学院补考重修管理系统研究 时间:2016 来源:南通大学杏林学院 关键词:WEB:补考重修管 ...
- postgresql从库提升为主库
一.停主库 1.查看当前连接 select pid,datname,usename,client_addr,client_port, application_name from pg_stat_act ...
- 神奇的 Object.defineProperty 解释说明
原文 : https://segmentfault.com/a/1190000004346467?utm_source=tuicool&utm_medium=referral 这个方法了不起啊 ...
- k8s 基础概念
摘录自k8s中文社区https://www.kubernetes.org.cn/course kubernetes 源自希腊文,意为舵手,k与s之间是8个字母,所以也叫k8s, docker就像一个个 ...
- 文字环绕和两栏自适应以及区域滚动插件iscroll.js
一.文字环绕效果:使用浮动 <div class="boxleft"></div> 我是一段文字我是一段文字我是一段文字我是一段文字我是一段文字我是一段文字 ...
- 浏览器事件循环 & nodejs事件循环
第1篇:如何理解EventLoop——宏任务和微任务篇 宏任务(MacroTask)引入 在 JS 中,大部分的任务都是在主线程上执行,常见的任务有: 渲染事件 用户交互事件 js脚本执行 网络请求. ...