问题链接
https://leetcode.com/explore/interview/card/top-interview-questions-easy/94/trees/631/
解题思路
递归查找中间值,并作为root节点,再找前后两段的中间值,作为左节点和右节点
代码
# 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
"""
if len(nums) == 0:
return None
midx = len(nums)/2
root = TreeNode(nums[midx])
leftNode = self.sortedArrayToBST(nums[:midx])
if leftNode:
root.left = leftNode
rightNode = self.sortedArrayToBST(nums[midx+1:])
if rightNode:
root.right = rightNode
return root