leetcode 109. Convert Sorted List to Binary Search Tree 源代码加详细思路和注释

本文介绍如何将一个升序排列的单链表转换为高度平衡的二叉搜索树。利用快慢指针技巧找到链表的中点作为根节点,并递归构造左右子树。

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

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

Subscribe to see which companies asked this question

题目分析:将排好序的链表转换成平衡二叉树。我们想一下怎么将排好序的数组转换成平衡二叉树,首先找到根节点,之后递归的构建左右子树。那么转换为链表,怎么找到根节点,想到常用的链表思路:快慢指针,快速找到中间位置的根节点。

public class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if(head==null) return null;
        if(head.next==null) return new TreeNode(head.val);
        return toBST(head,null);
        
    }
    
    public TreeNode toBST(ListNode head,ListNode tail)
    {
        if(head==tail) return null; //head是起始节点,tail是终止结点的下一个结点
        ListNode slow=head;
        ListNode fast=head;
        while(fast!=tail&&fast.next!=tail)//通过快慢指针快速找到根节点
        {
            fast=fast.next.next;
            slow=slow.next;
        }
        TreeNode res=new TreeNode(slow.val);
        res.left=toBST(head,slow);//递归的构建左子树,右子树
        res.right=toBST(slow.next,tail);
        return res;
       
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值