# 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
"""
def helper(left, right):
if left > right:
return None
# always choose left middle node as a root
p = (left + right) // 2
# inorder traversal: left -> node -> right
root = TreeNode(nums[p])
root.left = helper(left, p - 1)
root.right = helper(p + 1, right)
return root
return helper(0, len(nums) - 1)
树-108. 将有序数组转换为二叉搜索树-PYTHON
最新推荐文章于 2022-10-19 15:49:13 发布