109. Convert Sorted List to Binary Search Tree

一、题目

  1、审题

  2、分析

    给出一个数值有序的链表,将这个链表的节点组成一个二叉平衡树。

二、解答

  1、思路:

    采用的是二分查找的思想,利用递归进行实现。

    技巧:利用两个指针, slow 每次向前移动一个单位,fast 每次向前移动两个单位,当 fast 为空 或 fast 为要查找的元素时,此时 slow 即为开始位置到要查找元素的 mid 位置。

    

    public TreeNode sortedListToBST(ListNode head) {
     
        if(head == null)
            return null;
        
        return toBST(head, null);
    }
    
    
    private TreeNode toBST(ListNode head, Object tail) {

        if(head == tail)
            return null;
        
        ListNode slow = head;
        ListNode fast = head;
        
        // fast 向后移动两个单位,slow 向后移动一个单位,最终跳出循环时, slow 正好是 mid 位置
        while(fast != tail && fast.next != tail) {    
            fast = fast.next.next;
            slow = slow.next;
        }
        
        TreeNode root = new TreeNode(slow.val);
        root.left = toBST(head, slow);
        root.right = toBST(slow.next, tail);
        return root;
    }

    

原文地址:https://www.cnblogs.com/skillking/p/9734791.html