Use the middle number as the parent node and recursively build the left and right sub-tree.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
def helper(left, right):
if left >= right:
return None
mid = left + (right - left) // 2
return TreeNode(nums[mid], helper(left, mid), helper(mid+1, right))
return helper(0, len(nums))
Edited on 07/26/2021. Tidy the code.
No comments:
Post a Comment