108. Convert Sorted Array to Binary Search Tree
程序员文章站
2022-05-07 20:11:08
...
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
解题思路:升序数组构建而查找树,通过109的讲解(详情可见),我们发现最优解是中序遍历构建是最优解,而与升序链表不同的地方在于它的size是直接获取的;
class Solution {
private:
int count = 0;
vector<int> ls;
TreeNode* helpsortedArrayToBST(int size){
if (size == 0) return NULL;
TreeNode* root = new TreeNode(0);
root->left = helpsortedArrayToBST(size/2);
root->val = ls[count++];
root->right = helpsortedArrayToBST(size-size/2- 1);
return root;
}
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
ls.assign(nums.begin(),nums.end());
return helpsortedArrayToBST(nums.size());
}
};
结果如下:
上一篇: Iconfont使用的三种方式
推荐阅读
-
Convert Sorted Array to Binary Search Tree
-
Leetcode——108. Convert Sorted Array to Binary Search Tree
-
Leetcode 108. Convert Sorted Array to Binary Search Tree
-
Leetcode No.108 Convert Sorted Array to Binary Search Tree(c++实现)
-
convert-sorted-array-to-binary-search-tree 将有序数组转换为二叉搜索树
-
Convert Sorted Array to Binary Search Tree
-
108. Convert Sorted Array to Binary Search Tree
-
109. Convert Sorted List to Binary Search Tree
-
108. Convert Sorted Array to Binary Search Tree
-
538. Convert BST to Greater Tree && 1038. Binary Search Tree to Greater Sum Tree