# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
from typing import List
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
# 如果列表为空的话,就返回空节点
if nums == [] : return
# 取列表中间的那个值。当做根节点
mid = len(nums) // 2
mid_value = nums[mid]
root = TreeNode(mid_value)
# 列表左边的值为根节点的左儿子,
root.left = self.sortedArrayToBST(nums[:mid])
# 右边的值为根节点的右儿子
root.right = self.sortedArrayToBST(nums[mid + 1 :])
return root
内容来源于网络如有侵权请私信删除