Convert Sorted Array to Binary Search Tree

本文介绍如何将一个按升序排列的数组转换为高度平衡的二叉搜索树。平衡二叉树定义为任意节点的两个子树深度差不超过1。通过递归寻找数组中位数作为根节点,并分别构建左右子树,实现平衡二叉搜索树的构建。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

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

python代码实现:

# Definition for a binary tree node.
# class TreeNode:
#     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
        """
        size = len(nums)
        if size == 0:
            return None
        if size == 1:
            return TreeNode(nums[0])
        size //= 2
        root = TreeNode(nums[size])
        root.left = self.sortedArrayToBST(nums[:size])
        root.right = self.sortedArrayToBST(nums[size + 1:])
        return root

解题思路:

该问题是给定一个排序好的数组,然后根据这些数组中的数值生成一个等高度的二叉排序树。

解题点:
  • 等高:如果想生成等高的二叉树,那么根节点应该在拍好序的数组的中位数上
  • 二叉排序树:
    二叉排序树或者是一棵空树,或者是具有下列性质的二叉树:
    (1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;
    (2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值;
    (3)左、右子树也分别为二叉排序树;
    (4)没有键值相等的节点。
    因此,也可采用递归的思想,每次都去寻找中位数,然后生成树。
To convert the given array to a complete BST, we need to perform the following steps: 1. Sort the array in ascending order 2. Construct a complete binary tree using the sorted array 3. Perform inorder traversal of the binary tree and store the elements in the original array in the same order as the traversal Here's the implementation of the to_bst(lst) function in Python: ```python def to_bst(lst): # Sort the input list lst.sort() # Construct a complete binary tree using the sorted list n = len(lst) if n == 0: return lst root = lst[n // 2] left_subtree = to_bst(lst[:n // 2]) right_subtree = to_bst(lst[n // 2 + 1:]) binary_tree = [root] + left_subtree + right_subtree # Perform inorder traversal of the binary tree and store the elements in the original array inorder_traversal(binary_tree, lst, 0) return lst def inorder_traversal(binary_tree, lst, i): # Perform inorder traversal of the binary tree and store the elements in the original array n = len(binary_tree) if i >= n: return inorder_traversal(binary_tree, lst, 2 * i + 1) lst[i] = binary_tree[i] inorder_traversal(binary_tree, lst, 2 * i + 2) ``` The to_bst(lst) function takes in the input list and returns the same list after converting it to a complete BST. The function first sorts the input list in ascending order. It then constructs a complete binary tree using the sorted list by recursively dividing the list into two halves and setting the middle element as the root of the binary tree. Finally, the function performs an inorder traversal of the binary tree and stores the elements in the original list in the same order as the traversal.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

. . . . .

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值