LeetCode_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.

思路:二叉查找树的中序遍历就是排序的数,那么我们可以通过中序遍历来构建这个树

直接看代码,下面一般是改进的 ,这里题目要求的是,当节点是偶数的时候,以n/2+1个作为中间节点。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; next = null; }
 * }
 */
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
//二叉查找树的中序遍历就是排序的数,那么我们可以通过中序遍历来构建这个树
public class Solution {
    
    public TreeNode sortedListToBST(ListNode head) {
        if(head==null)
            return null;
        if(head.next==null)
            return new TreeNode(head.val);
        //至少有两个节点才能用快慢节点切割,不然节点为1的时候 会出现分为 1,0这样的死循环
        ListNode fast=head;
        ListNode slow=head;
        ListNode pre=null;
        while(fast!=null&&fast.next!=null){
            pre=slow;
            slow=slow.next;
            fast=fast.next.next;
        }
        if(pre!=null)
            pre.next=null;
        ListNode mid=slow;//慢指针指向的就是中间节点
        ListNode nextHead=slow.next;

        TreeNode node=new TreeNode(mid.val);
        if(pre==null)
            node.left=sortedListToBST(null);
        else
            node.left=sortedListToBST(head);
        node.right=sortedListToBST(nextHead);
        return node;
    }
    
    //代码改进
    public TreeNode sortedListToBST(ListNode head) {
        return sortedListToBST(head,null);
    }
    private TreeNode sortedListToBST(ListNode head,ListNode end){
        if(head==end)
            return null;
        ListNode fast=head;
        ListNode slow=head;
        while(fast!=end&&fast.next!=end){
            fast=fast.next.next;
            slow=slow.next;
        }
        TreeNode root=new TreeNode(slow.val);
        root.left=sortedListToBST(head,slow);
        root.right=sortedListToBST(slow.next,end);
        return root;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值