标签:
给定一个升序的序列,将它转化为高度平衡的二叉搜索树。
注意点:
例子:
输入: nums = [1,2,3]
输出:
2
/ 1 3
平衡二叉搜索树的要求是每个节点左右子树的高度差最多为1。那只要取序列的中间数作为根节点,左边的序列再组成它的左子树,右边的序列组成它的右子树,递归完成构造。
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
return self._sortedArrayToBST(nums, 0, len(nums))
def _sortedArrayToBST(self, nums, left, right):
if left == right:
return None
mid = (left + right) >> 1
root = TreeNode(nums[mid])
root.left = self._sortedArrayToBST(nums, left, mid)
root.right = self._sortedArrayToBST(nums, mid + 1, right)
return root
if __name__ == "__main__":
None
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
LeetCode Convert Sorted Array to Binary Search Tree
标签:
原文地址:http://blog.csdn.net/u013291394/article/details/50697682