Convert Sorted Array to Binary Search Tree @ LeetCode (Python)
kitt
posted @ 2014年3月07日 19:41
in LeetCode
, 2804 阅读
递归。每次数组的中点元素为root, 再递归地建立左右子树。
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param num, a list of integers # @return a tree node def sortedArrayToBST(self, num): return self.createBST(num, 0, len(num) - 1) def createBST(self, num, start, end): if start > end: return None mid = (start + end) / 2 root = TreeNode(num[mid]) root.left = self.createBST(num, start, mid - 1) root.right = self.createBST(num, mid + 1, end) return root