109.有序链表转换二叉搜索树

2020/12/4

# Heading

    109.有序链表转换二叉搜索树 (opens new window)

    Tags: algorithms zenefits linked-list depth-first-search

    Langs: c cpp csharp golang java javascript kotlin php python python3 racket ruby rust scala swift typescript

    • algorithms
    • Medium (76.09%)
    • Likes: 450
    • Dislikes: -
    • Total Accepted: 70K
    • Total Submissions: 92K
    • Testcase Example: '[-10,-3,0,5,9]'

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

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

    示例:

    给定的有序链表: [-10, -3, 0, 5, 9],
    
    一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
    
          0
         / \
       -3   9
       /   /
     -10  5
    
    /*
     * @lc app=leetcode.cn id=109 lang=javascript
     *
     * [109] 有序链表转换二叉搜索树
     */
    
    // @lc code=start
    /**
     * 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) {
        if (head === null) return null;
        if (head.next === null) return new TreeNode(head.val);
        //计算length
        let length = 0;
        let p = head;
        while (p){
            length++;
            p = p.next;
        }
        //找到中点,偶数为偏右的那个值
        let i = -1,prev;
        p = head;
        while (++i < ~~(length/2)) {
            prev = p;
            p = p.next;
        }
        //中点前后断链
        prev.next = null;
        let right = p.next;
        //递归构造二叉树
        return new TreeNode(p.val, sortedListToBST(head), sortedListToBST(right))
    };
    // @lc code=end
    
    
    // @after-stub-for-debug-begin
    module.exports = sortedListToBST;
    // @after-stub-for-debug-end
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56