LeetCode: 108. Convert Sorted Array to Binary Search Tree
原创
©著作权归作者所有:来自51CTO博客作者yanglingwell的原创作品,请联系作者获取转载授权,否则将追究法律责任
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:
题目大意: 根据给定的有序数组,生成一种可能的平衡二叉树。
解题思路
中位数作为根节点,中位数左/右边的所有元素作为左/右子树的节点,用同样的方法处理左边和右边的元素,生成左子树和右子树。
AC 代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
private:
// 将 nums 数组中的 [beg, end) 区间转换成平衡二叉树 BST.
TreeNode* sortedArrayToBSTRef(vector<int>& nums, int beg, int end)
{
if(beg >= end) return nullptr;
// 中位数作为根节点
int mid = (beg + end)/2;
TreeNode* root = new TreeNode(nums[mid]);
// 同样的操作生成左/右子树
root->left = sortedArrayToBSTRef(nums, beg, mid);
root->right = sortedArrayToBSTRef(nums, mid+1, end);
return root;
}
public:
TreeNode* sortedArrayToBST(vector<int>& nums)
{
return sortedArrayToBSTRef(nums, 0, nums.size());
}
};