https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree/
    [制卡]

    快慢指针

    1. const sortedListToBST = (head) => {
    2. if (head == null) return null;
    3. let slow = head;
    4. let fast = head;
    5. let preSlow; // 保存slow的前一个节点
    6. while (fast && fast.next) {
    7. preSlow = slow; // 保存当前slow
    8. slow = slow.next; // slow走一步
    9. fast = fast.next.next; // fast走两步
    10. }
    11. const root = new TreeNode(slow.val); // 根据slow指向的节点值,构建节点
    12. if (preSlow != null) { // 如果preSlow有值,即slow左边有节点,需要构建左子树
    13. preSlow.next = null; // 切断preSlow和中点slow
    14. root.left = sortedListToBST(head); // 递归构建左子树
    15. }
    16. root.right = sortedListToBST(slow.next); // 递归构建右子树
    17. return root;
    18. };
    
    function sortedListToBST(head: ListNode | null): TreeNode | null {
      return build(head, null);
    }
    
    function build(left: ListNode | null, right: ListNode | null): TreeNode | null {
      if (left == right) {
        return null
      }
      let mid: ListNode = getMid(left, right) as ListNode
      let root = new TreeNode(mid.val)
      root.left = build(left,mid)
      root.right = build(mid.next,right)
      return root
    }
    
    function getMid(left: ListNode | null, right: ListNode | null): ListNode | null {
      // 快慢指针
      let slow = left;
      let fast = left;
      while (fast != null && fast.next != right) {
        slow = slow != null ? slow.next : null
        fast = fast.next != null ? fast.next.next : null
      }
      return slow
    }