Leetcode 108

Convert Sorted Array to Binary Search Tree

Problem

Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

Algorithm

Recursion. Divide the tree into two sub-trees in the middle.

Code

# 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:
        numsL = len(nums)
        if not numsL:
            return []
        
        def dfs(L, R):
            if L > R:
                return None
            M = (L + R) // 2
            L = dfs(L, M-1)
            R = dfs(M+1, R)
            return TreeNode(nums[M], L, R)
        
        return dfs(0, numsL-1)
上一篇:C#把短日期转换为datatime: 如"2019-02-01"


下一篇:LeetCode 401. Binary Watch(二进制手表)