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:
0
/ \
-3 9
/ /
-10 5
算法
一开始想复杂了,以为要动态的去改变树的结构是它变成平衡二叉树,其实很简单,因为是排好序的数组,只需要每次取中值,然后递归左子树,递归右子树即可,这样构成的二叉树一定是平衡的。
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* sortToBST(int* nums, int left, int right){
if(left>right){
return NULL;
}
int mid = (left + right) / 2;
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = nums[mid];
root->left = sortToBST(nums, left, mid - 1);
root-> right = sortToBST(nums, mid + 1, right);
return root;
}
struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
return sortToBST(nums, 0, numsSize-1);
}