Converting an ordered linked list to a binary search tree

1. Demand

  • Given a singly linked list, the elements in it are sorted in ascending order and converted into a highly balanced binary search tree;

  • In this question, a highly balanced binary tree means that the absolute value of the height difference between the left and right subtrees of each node of a binary tree does not exceed 1;

Second, the speed pointer

2.1 Thinking analysis

  1. For an ordered linked list, if you want to find its middle element, you need to use the fast and slow pointers. Each time the fast pointer moves one more space than the slow pointer. When the fast pointer points to null or the next element of the fast pointer points to null, it is slow. The pointer points to the middle element;
  2. Except for step 1, the basic idea is the same as "converting an ordered array into a binary search tree";

2.2 Code implementation

class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if(head == null) return null;
        return helper(head, null);
    }
    //符合左闭右开
    public TreeNode helper(ListNode head, ListNode tail) {
        if(head == tail) return null;
        ListNode fast = head;
        ListNode slow = head;
        while(fast != tail && fast.next != tail) {
            fast = fast.next.next;
            slow = slow.next;
        }
        TreeNode root = new TreeNode(slow.val);
        root.left = helper(head, slow);
        root.right = helper(slow.next, tail);
        return root;
    }
}

2.3 Complexity analysis

  • The time complexity is O(N), and the establishment of a binary search tree requires traversal of all linked list nodes;
  • The space complexity is O(log_2N);

Guess you like

Origin blog.csdn.net/Sruggle/article/details/113445427