An ordered array in accordance with the ascending order, is converted to a highly balanced binary search tree.
In this problem, a highly balanced binary tree is a binary tree refers to the left and right sub-tree of each node is the height difference between the absolute value of not more than 1.
Example:
Given an ordered array: [-10, -3,0,5,9],
One possible answer is: [0, -3,9, -10, null, 5], it can be expressed below this height balanced binary search tree:
0
/ \
-3 9
/ /
-10 5
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode*DFS(int* nums, int numsSize)
{
if(numsSize<=0)return NULL;
struct TreeNode*ret=(struct TreeNode*)malloc(sizeof(struct TreeNode));
if(numsSize==1)
{
ret->val=nums[0];
ret->left=NULL;
ret->right=NULL;
}
else
{
int pos=(numsSize)/2;
ret->val=nums[pos];
ret->left=DFS(nums,pos);
ret->right=DFS(nums+pos+1,numsSize-pos-1);
}
return ret;
}
struct TreeNode* sortedArrayToBST(int* nums, int numsSize){
return DFS(nums,numsSize);
}
When execution: 12 ms, beat the 99.04% of all users in C submission
Memory consumption: 19.1 MB, defeated 100.00% of all users in C submission