109. Convert Sorted List to Binary Search Tree

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

思路:还是找mid,不过这次用双指针。完美的list

public class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if (head==null) return null;
        TreeNode root = addNode(head,null);
        return root;
    }

    public TreeNode addNode(ListNode head, ListNode tail){
        ListNode fast = head;
        ListNode slow = head;
        if (head==tail) return null;

        while(fast!=tail && fast.next!=tail){
            fast = fast.next.next;
            slow = slow.next;
        }

        TreeNode root = new TreeNode(slow.val);
        root.left = addNode(head,slow);
        root.right = addNode(slow.next,tail);
        return root;
    }
}

results matching ""

    No results matching ""