LeetCode108:Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

LeetCode:链接

解题思路:由于要求二叉查找树是平衡的。所以我们可以选在数组的中间那个数当树根root,然后这个数左边的数组为左子树,右边的数组为右子树,分别递归产生左右子树就可以了。

# 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
        """
        if not nums:
            return None
        #找到中间节点
        mid = len(nums) // 2  
        #当前节点为根节点
        root = TreeNode(nums[mid])
        #小于当前根节点的作为左子树
        root.left = self.sortedArrayToBST(nums[:mid])
        #大于当前根节点的作为右子树
        root.right = self.sortedArrayToBST(nums[mid+1:])
        return root

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/84290841