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.
题目大意:
给定一个升序排列的数组,将其转换成一个高度平衡的BST(二叉搜索树)。其中BST指任意一个节点的两棵子树高度差不大于1。
思路:
该题和将链表转换成二叉树思路一致,但本题简单在数组,因为数组的中间位置可以简单的通过下标去访问。直接给出代码
代码:
/**
* 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 {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
TreeNode* root = NULL;
if(nums.empty())
return root;
helper(root, nums, 0, nums.size()-1);
return root;
}
void helper(TreeNode* & root, vector<int>& nums, int start, int end){
if(start > end)
return;
int index = start + (end - start + 1)/2;
root = new TreeNode(nums[index]);
helper(root->left, nums, start, index-1);
helper(root->right, nums, index+1, end);
}
};