Leetcode(java,python题解):109.有序链表转换二叉搜索树

将升序排列的链表转换为高度平衡的二叉搜索树,使用中序遍历模拟和二分法实现。示例:输入[-10, -3, 0, 5, 9],输出平衡BST。提供Java和Python解题代码。" 126673626,12924305,C++继承深入解析,"['C++', '面向对象', '继承']

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

109.有序链表转换二叉搜索树

题目描述

Leetcode:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

示例:

给定的有序链表: [-10, -3, 0, 5, 9],

一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:


解题思路
中序遍历模拟,用二分法来递归模拟

java代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private ListNode head;

    private int findSize(ListNode head){
        ListNode ptr = head;
        int c = 0;
        while(ptr != null){
            ptr = ptr.next;
            c += 1;
        }
        return c;
    }

    public TreeNode sortedListToBST(ListNode head) {
        int size = this.findSize(head);

        this.head = head;
        return this.convertToBST(0, size - 1);
    }

    public TreeNode convertToBST(int l, int r){
        if(l > r) return null;
        int mid = (l + r) / 2;
        TreeNode left = this.convertToBST(l, mid - 1);
        TreeNode node = new TreeNode(head.val);
        node.left = left;
        this.head = this.head.next;
        node.right = this.convertToBST(mid + 1, r);
        return node;
    }
}

python代码

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def findSize(self, head: ListNode) -> int:
        ptr = head
        c = 0
        while ptr:
            ptr = ptr.next
            c +=1
        return c

    def sortedListToBST(self, head: ListNode) -> TreeNode:
        size = self.findSize(head)

        def convert(l: int, r: int) -> TreeNode:
            nonlocal head
            if l > r:
                return None
            mid = (l + r) // 2
            left = convert(l, mid - 1)
            node = TreeNode(head.val)
            node.left = left
            head = head.next
            node.right = convert(mid + 1, r)
            return node

        return convert(0, size - 1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值