原題地址:http://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
題意:將一個排序好的數組轉換為一顆二叉查找樹,這顆二叉查找樹要求是平衡的。
解題思路:由於要求二叉查找樹是平衡的。所以我們可以選在數組的中間那個數當樹根root,然后這個數左邊的數組為左子樹,右邊的數組為右子樹,分別遞歸產生左右子樹就可以了。
代碼:
# Definition for a binary tree node # 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): length = len(num) if length == 0: return None if length == 1: return TreeNode(num[0]) root = TreeNode(num[length / 2]) root.left = self.sortedArrayToBST(num[:length/2]) root.right = self.sortedArrayToBST(num[length/2 + 1:]) return root