给定一个元素各不相同的有序序列int[] vals(升序排列),请编写算法创建一棵高度最小的二叉查找树,并返回二叉查找树的高度。
# -*- coding:utf-8 -*- class MinimalBST: def buildMinimalBST(self, vals): # write code here if len(vals)<=0: return None root = self.buildBST(vals,0,len(vals)-1) height = self.getHeight(root) return height def buildBST(self,vals,left,right): if left>right: return None mid = (left + right)/2 root = TreeNode(vals[mid]) root.left = self.buildBST(vals,left,mid-1) root.right = self.buildBST(vals,mid+1,right) return root def getHeight(self, root): if root is None: return 0 if self.getHeight(root.left)>self.getHeight(root.right): return self.getHeight(root.left)+1 else: return self.getHeight(root.right)+1
# -*- coding:utf-8 -*- class MinimalBST: def buildMinimalBST(self, vals): import math return int(math.log(len(vals), 2)) + 1