美文网首页
LeetCode 第109题:有序链表转换二叉搜索树

LeetCode 第109题:有序链表转换二叉搜索树

作者: 放开那个BUG | 来源:发表于2020-08-13 23:56 被阅读0次

1、前言

题目描述

2、思路

可以采用将有序数转化为二叉搜索树的思路,只不过链表找节点使用的快慢指针,最后的 slow 就是中点,然后基于 [head, slow] 根 [slow + 1, tail] 两部分递归。

3、代码

/**
 * 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 {
    public TreeNode sortedListToBST(ListNode head) {
        if(head == null){
            return null;
        }

        // 尾节点为 null
        return dfs(head, null);
    }


    private TreeNode dfs(ListNode head, ListNode tail){
        if(head == tail){
            return null;
        }

        ListNode slow = head;
        ListNode fast = head;

        // 关于这一点,fast 是不等于 tail,注意
        while(fast != tail && fast.next != tail){
            slow = slow.next;
            fast = fast.next.next;
        }
        
        TreeNode root = new TreeNode(slow.val);
        root.left = dfs(head, slow);
        root.right = dfs(slow.next, tail);

        return root;
    }
}

相关文章

网友评论

      本文标题:LeetCode 第109题:有序链表转换二叉搜索树

      本文链接:https://www.haomeiwen.com/subject/idwddktx.html