LeetCode108 - (easy) Convert Sorted Array to Binary Search Tree
文章目录
Task
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
|
|
Solution
- 要想高度平衡,需要每个节点的左右子树中的节点数相同,即每个子树的根节点都选在该子树对应的数组区域的中心
- 如图,每次递归时将数组二分并将二分点作为该子树的根节点
时间复杂度
:要遍历每一个节点是O(n),处理每个节点是随机索引O(1),故总时间复杂度是O(n)空间复杂度
:取决于递归深度,O(logn)- 实现:
|
|