LeetCode - Convert Sorted List to Binary Search Tree

本文介绍了一种将有序链表转换为平衡二叉搜索树的方法。通过使用双指针技巧找到中间节点作为根节点,并递归地构建左右子树。文章提供了详细的Java实现代码。

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

https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/

这道题用递归很简单,每次把中间结点找到,中间结点是root,然后递归左半部份,建左子树,递归右半部份,建右子树。

找中间结点的算法就是two pointer的方法,一个每次前进一步,一个每次前进两步,知道到达tail为止。注意每次循环都需要检查 p2!=tail p2.next!=tail, 因为p2每次前进两步,如果只检查p2 != tail,可能把tail跳过了。

注意,当只有两个节点的时候,是没有左子树的,需要注意这种情况。

public class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if(head==null) return null;
        if(head.next==null){
            TreeNode root = new TreeNode(head.val);
            return root;
        }
        ListNode tail = head;
        while(tail.next!=null){
            tail = tail.next;
        }
        TreeNode root = getTree(head, tail);
        return root;
    }
    
    public TreeNode getTree(ListNode head, ListNode tail){
        if(head==tail){
            TreeNode root = new TreeNode(head.val);
            return root;
        }
        if(head==null||tail==null) return null;
        ListNode p1 = head;
        ListNode p2 = head;
        ListNode pre = head;
        while(p2 != tail && p2.next!=tail){
            pre = p1;
            p1 = p1.next;
            p2 = p2.next.next;
        }
        TreeNode root = new TreeNode(p1.val);
        if(head!=p1) root.left = getTree(head, pre);
        root.right = getTree(p1.next, tail);
        return root;
    }
}

http://blog.youkuaiyun.com/fightforyourdream/article/details/16940205

这里的方法是用一边开的区间来避免找tail node和不需要保留pre指针。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值