首页 > 其他 > 详细

Cracking the Code Interview 4.3 Array to Binary Tree

时间:2015-06-15 23:34:34      阅读:188      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!