1. 程式人生 > >JavaScript刷LeetCode -- 109. Convert Sorted List to Binary Search Tree

JavaScript刷LeetCode -- 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.

  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.

二、題目大意

  將一個有序連結串列轉化為BST。

三、解題思路

  二分查詢的方式不斷的遞迴建立節點,需要這裡給的是連結串列資料結構,相比較陣列,在查詢中心點以及分割成左右兩部分的處理差異性很大。

四、程式碼實現

const sortedListToBST = head => {
  if (!head) {
    return null
  }
  if (!head.next) {
    return new TreeNode(head.val)
  }

  const mid = findMid(head)
  const root = new TreeNode(mid.val)

  root.left = sortedListToBST(head)
  root.right = sortedListToBST(mid.next)

  return root

  function findMid (head) {
    let slow = head
    let fast = head
    let slowPre = null
    while (fast && fast.next) {
      slowPre = slow
      slow = slow.next
      fast = fast.next.next
    }
    // 分割連結串列
    slowPre.next = null
    return slow
  }
}

  如果本文對您有幫助,歡迎關注微信公眾號,為您推送更多內容,ε=ε=ε=┏(゜ロ゜;)┛。