首页 > 其他 > 详细

LeetCode:Convert Sorted Array to Binary Search Tree

时间:2014-03-23 20:54:00      阅读:420      评论:0      收藏:0      [点我收藏+]

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

Solution:

bubuko.com,布布扣
BinaryTree* sortedArrayToBST(int arr[], int start, int end) {
  if (start > end) return NULL;
  // same as (start+end)/2, avoids overflow.
  int mid = start + (end - start) / 2;
  BinaryTree *node = new BinaryTree(arr[mid]);
  node->left = sortedArrayToBST(arr, start, mid-1);
  node->right = sortedArrayToBST(arr, mid+1, end);
  return node;
}

BinaryTree* sortedArrayToBST(int arr[], int n) {
  return sortedArrayToBST(arr, 0, n-1);
}
bubuko.com,布布扣

LeetCode:Convert Sorted Array to Binary Search Tree,布布扣,bubuko.com

LeetCode:Convert Sorted Array to Binary Search Tree

原文:http://www.cnblogs.com/yeek/p/3619299.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!