美文网首页
108. Convert Sorted Array to Bin

108. Convert Sorted Array to Bin

作者: 羲牧 | 来源:发表于2020-05-29 13:14 被阅读0次

    根据已排序数组创建平衡二叉查找树

    需要认识到,平衡二叉查找树的中序遍历即为有序数组。

    递归解法:

    # 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:
            return self.createBST(nums, 0, len(nums) - 1)
        
        def createBST(self, nums, left, right):
            if left > right:
                return None
            mid = left + (right-left)//2
            print(mid)
            # print(nums[mid])
            root = TreeNode()
            root.val = nums[mid]
            root.left = self.createBST(nums, left, mid-1)
            root.right = self.createBST(nums, mid+1, right)
            return root
            
    
    

    相关文章

      网友评论

          本文标题:108. Convert Sorted Array to Bin

          本文链接:https://www.haomeiwen.com/subject/hxpxzhtx.html