初级算法练习第十节

84 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第24天,点击查看活动详情

1. 引言

接下来继续下一题开展对应leetcode 习题课中初级算法题目的练习,这个就当我的学习笔记了,大家一起交流,让我们一起学习变得更好吧! 官网地址:leetcode.cn/leetbook/re…

2. 题型

1.将有序数组转换为二叉搜索树 追加说明: 给你一个整数数组 nums ,其中元素已经按 升序 排列,请你将其转换为一棵 高度平衡 二叉搜索树。

高度平衡 二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树。

image

示例1:
输入:nums = [-10,-3,0,5,9]
输出:[0,-3,9,-10,null,5]
解释:[0,-10,5,null,-3,null,9] 也正确答案之一:

image

示例2:
输入:nums = [-10,-3,0,5,9]
输出:[0,-3,9,-10,null,5]
解释:[0,-10,5,null,-3,null,9] 也正确答案之一:

image

提示:

1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums 按 严格递增 顺序排列

思路:
首先,先找到中点,作为“树根”,中点的值为数组中间值;以中点左侧的虚列递归构建左子树;以右点左侧的虚列递归构建右子树;开始解题前先排除临界值,然后实例化节点头部,获取到中点左侧序号值和右侧序号值,节点的左侧树为递归函数数组位从0到中点位置,右侧为数组右侧树节点right;其中左树节点为中点左侧前一节点,右侧节点为中点右侧后一节点;当左侧节点大于0,说明左侧有左子树;同理,当右侧节点小于数组本身长度说明存在右子树,这时候我们就可以通过递归方法,获取左子树0到中点的树型和右子树;最后返回节点; 解答:

 
/**
 * 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 {number[]} nums
 * @return {TreeNode}
 */
function TreeNode(val) {
    this.val = val;
    this.left = this.right = null;
}

var sortedArrayToBST = function(nums) {
    // 因为涉及到递归,所以必然会有数组为空的情况
    if(!nums.length) {
        return null;
    }

    // 找到序列中点:
    const headIndex = Math.floor(nums.length / 2);

    // 实例化节点头部
    const head = new TreeNode(nums[headIndex]);
    let temp = head;
    let left = headIndex - 1;
    let right = headIndex + 1;
    // 因为是有序升序列表,则当前头部索引的左侧应该都在树的左子树,同理右子树
    if(left >=0) {
        // 左侧有节点,对左侧节点递归,形成左子树
        head.left = sortedArrayToBST(nums.slice(0, headIndex));
    }
    if(right < nums.length) {
        // 右侧有节点,对右侧节点递归,形成右子树
        head.right = sortedArrayToBST(nums.slice(right));
    }
    // 返回节点
    return head;
};