108. Convert Sorted Array to Binary Search Tree
程序员文章站
2022-05-18 19:36:16
...
problems:
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
tips:
参考博客:https://blog.csdn.net/u012814856/article/details/77894863 二叉树中采用递归方式求解问题。
solution:
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums)
{
if(!nums.size()) return NULL;
int mid = nums.size()/2;
TreeNode *node=new TreeNode(nums[mid]);
vector<int> leftnode = vector<int>(nums.begin(),nums.begin()+mid);
vector<int> rightnode = vector<int>(nums.begin()+mid+1,nums.end());
if(mid != 0)
node->left = sortedArrayToBST(leftnode);
if(mid != nums.size()-1)
node->right = sortedArrayToBST(rightnode);
return node;
}
};
推荐阅读
-
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