Cracking the Code Interview 4.3 Array to Binary Tree

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 part 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

 

posted @ 2015-06-15 22:00  lilixu  阅读(132)  评论(0编辑  收藏  举报