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

Cracking the Code Interview 4.3 Array to Binary Tree

时间:2015-06-15 23:35:50      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

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

1.Divide the array equally into left part and right part, the mid value will be the root.

2.Recall the function to the left and right pat of the array.

def array_to_tree(a)
  to_tree(a,0,a.length-1)
end

def to_tree(a,s,e)
  return if s > e
  n = treeNode.new(a[(s+e)/2])
  n.left, n.right = to_tree(a,s,(s+e)/2-1), to_tree(a,(s+e)/2+1,e)
  n
end

 

Cracking the Code Interview 4.3 Array to Binary Tree

标签:

原文地址:http://www.cnblogs.com/lilixu/p/4579345.html

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