Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1562521
  • 博文数量: 327
  • 博客积分: 10000
  • 博客等级: 上将
  • 技术积分: 3556
  • 用 户 组: 普通用户
  • 注册时间: 2005-04-05 21:28
个人简介

东黑布衣,流浪幽燕。 真诚善良,值得信赖。

文章分类

全部博文(327)

我的朋友

分类: BSD

2019-01-06 23:46:13

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. }



















阅读(2356) | 评论(0) | 转发(0) |
0

上一篇:LeetCode 0094 0144

下一篇:没有了

给主人留下些什么吧!~~