108Convert Sorted Array to Binary Search Tree
Easy

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


  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  * int val;
  5.  * struct TreeNode *left;
  6.  * struct TreeNode *right;
  7.  * };
  8.  */
  9. struct TreeNode* build(int* nums,int st,int ed){
  10.     struct TreeNode* r;
  11.     if(st>ed)return NULL;
  12.     int md = st+(ed-st)/2;
  13.     r = (struct TreeNode*)malloc(sizeof(struct TreeNode));
  14.     r->val = nums[md];
  15.     r->left = build(nums,st,md-1);
  16.     r->right = build(nums,md+1,ed);
  17.     return r;
  18. }
  19. struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
  20.     return build(nums,0,numsSize-1);
  21. }



















10-23 22:37