[LeetCode 109] Convert Sorted List to Binary Search Tree (medium)

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

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted linked list: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

Solution: recursion

  1. 思路与108一致,只是此处给的是linked list,需要对linked list做处理
  2. middle node时,用快慢指针。找到middle nodeprev node
    -10 -> -3-> 0 -> 5 ->  9
          prev  slow      fast
    
  3. prev.next == null, 这样将linked list分成2段。
    • 原始的head到prev用于构建左子树
    • slow.next到尾用于构建右子树
  4. Base Case:
    • root == null, return null
    • root是链表中唯一节点,即root.next == null, 直接返回该节点
/**
 * 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;
        }
        
        if (head.next == null) {
            return new TreeNode (head.val);
        }
        
        // find the middle 
        ListNode fast = head;
        ListNode slow = head;
        ListNode prev = new ListNode (0);
        prev.next = head;
        
        while (fast != null && fast.next != null) {
            slow = slow.next;
            prev = prev.next;
            fast = fast.next.next;
        }
        
        // cut the list into 2 pieces
        prev.next = null;
        
        // construct the current node and its left/right child
        TreeNode root = new TreeNode (slow.val);
        TreeNode left = sortedListToBST (head);
        TreeNode right = sortedListToBST (slow.next);
        
        root.left = left;
        root.right = right;
        
        return root;
    }
}

你可能感兴趣的:([LeetCode 109] Convert Sorted List to Binary Search Tree (medium))