1.描述
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
2.分析
3.代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* BST(int* nums, int from, int to) {
if (from > to) return NULL;
int mid = (from + to) / 2;
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = nums[mid];
node->left = BST(nums, from, mid - 1);
node->right = BST(nums, mid + 1, to);
return node;
}
struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
if (NULL == nums || 0 >= numsSize) return NULL;
return BST(nums, 0, numsSize - 1);
}
网友评论