【算法学习】有序链表转平衡二叉树

247 阅读1分钟

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

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 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 arr = []
    // 将链表的值存入数组
    while(head) {
        arr.push(head.val)
        head = head.next
    }
    const getBST =(start,end) => {
        // 节点不存在返回null
        if(start > end) {return null}
        // 头尾相加右移一位,得到向下取整的中间值
        let mid = (start + end) >>> 1
        // 创建节点
        let root = new TreeNode(arr[mid])
        // 递归调用填充子节点
        root.left = getBST(start,mid-1)
        root.right = getBST(mid+1,end)
        return root
    }
    // 由于数组是从0开始的,所以end取arr的长度-1
     return getBST(0,arr.length-1)
}