题目描述
题目链接: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.
例子
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
解题思路
由于已经给定了一个排序数组,所以构建高度平衡二叉搜索树比较简单,只需要取中间值作为根结点,对于两侧子数组进行递归操作,返回的根结点分别作为左右子树即可,代码如下:
1 | /** |
- 时间复杂度: O(n)
- 空间复杂度: O(n) — n 个节点作为新的二叉搜索树
GitHub 代码同步地址: 108.ConvertSortedArrayToBinarySearchTree.cpp
其他题目:
GitHub: Leetcode-C++-Solution
博客: Leetcode-Solutions