[leetcode] @python Convert Sorted List to Binary Search Tree

本文探讨了如何自底向上构建二叉搜索树(BST),并介绍了将单链表转换为BST的方法,包括定义节点类和构建BST的过程。

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

好像可以自底向上构造BST吧,不过我是转成array做的

# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param head, a list node
    # @return a tree node
    def sortedListToBST(self, head):
        if head is None: return None
        array = self.toArray(head)
        return self.buildBST(array, 0, len(array)-1)

    def buildBST(self, array, left, right):
        if left > right: return None
        mid = (left + right) / 2
        root = TreeNode(array[mid])
        root.left = self.buildBST(array, left, mid-1)
        root.right = self.buildBST(array, mid+1, right)
        return root

    def toArray(self, head):
        rst = []
        while head is not None:
            rst.append(head.val)
            head = head.next
        return rst
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值