Skip to content

Latest commit

 

History

History
137 lines (114 loc) · 3.41 KB

20200818-109.convert-sorted-list-to-binary-search-tree.md

File metadata and controls

137 lines (114 loc) · 3.41 KB

109.convert-sorted-list-to-binary-search-tree.

题目链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree/

参考链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree/solution/you-xu-lian-biao-zhuan-huan-er-cha-sou-suo-shu-1-3/

题目

给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

示例 :

给定的有序链表: [-10, -3, 0, 5, 9],

一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:

      0
     / \
   -3   9
   /   /
 -10  5

解题

思路[1]二分法

  • 统计长度,生成节点,放入数组,则中点就是根节点
  • 使用二分法不断寻找中点,生成二叉树

代码

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {ListNode} head
 * @return {TreeNode}
 */
var sortedListToBST = function(head) {
  const BET_ARR = []
  while(head){
    let node = new TreeNode(head.val);
    head = head.next;
    BET_ARR.push(node)
  }
  const helper = function(left, right) {
    if(left > right){
      return null
    }
    let mid = (left + right) >> 1;
    let root = BET_ARR[mid];
    root.left = helper(left, mid - 1);
    root.right = helper(mid + 1, right);
    return root
  }
  return helper(0, BET_ARR.length - 1)
};

思路[2]分治+中序遍历

  • 与思路1的区别在于这个方法不使用数组缓存节点,也不提前生成几点,在遍历过程中生成,也是二分法分片进行处理
  • 首先计算链表长度,用于计算中点,进行分治,对每次递归进行中序遍历,即先给节点左树赋值,再给节点赋值,最后给右树赋值

代码

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {ListNode} head
 * @return {TreeNode}
 */
var sortedListToBST = function(head) {
  let head_cache = head
  // 统计长度
  let length = 0;
  while (head != null) {
    ++length;
    head = head.next;
  }
  // 传入左右
  const helper = function(left, right) {
    if(left > right){
      return null
    }
    const mid = (left + right) >> 1;
    let root = new TreeNode()
    root.left = helper(left, mid - 1);
    root.val = head_cache.val;
    head_cache = head_cache.next;
    root.right = helper(mid + 1, right);
    return root
  }
  return helper(0, length - 1)
};

思考

  • 二叉搜索树,中序遍历!!!!!
  • 二叉搜索树,中序遍历!!!!!
  • 二叉搜索树,中序遍历!!!!!