二分法+递归即可,许久不写二叉树,已经有些遗忘了,正好复习一下。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* helper(int* nums, int left, int right)
{
if(left > right) return NULL;
int middle = (left + right) / 2;
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = nums[middle];
root->left = helper(nums, left, middle-1);
root->right = helper(nums, middle+1, right);
return root;
}
struct TreeNode* sortedArrayToBST(int* nums, int numsSize){
return helper(nums, 0, numsSize-1);
}