码迷,mamicode.com
首页 > 其他好文 > 详细

CC150 4.3

时间:2014-11-27 08:04:10      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:interview

4.3 Given a sorted (increasing order) array, write an algorithm to create a binary tree with minimal height.


[1, 2, 4, 5, 6]


Create a BT with min height. => balanced tree.

Node build(int array)
{
  return build(array, 0, array.length - 1, null);
}

O(log n)
private Node build(int[] array, int from, int to, Node father)
{
  if (from > to)
    return null;
    
  int middle = (from + to) / 2;
  Node n = new Node(middle);
  
  n.father = father;
  n.left = build(array[], from, middle - 1, n);
  n.right = build(array[], middle + 1, to, n);
  
  return n;
}


CC150 4.3

标签:interview

原文地址:http://7371901.blog.51cto.com/7361901/1583042

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!