Cracking the Code Interview 4.3 Array to Binary Tree

时间:2023-03-09 16:19:43
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