algorighm/top-interview-leetcode150/divide/108将有序数组转换为二叉树搜索树.js

39 lines
1.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 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}
*/
const sortedArrayToBST = function (nums) {
};
function TreeNode(val, left, right) {
this.val = (val === undefined ? 0 : val);
this.left = (left === undefined ? null : left);
this.right = (right === undefined ? null : right);
}
/*
用数组的中间值作为根节点,然后递归的将左半部分和右半部分处理成一颗二叉搜索树,并设置成根节点的左右子树
*/
function f1(left, right, nums) {
// 如果left > right, 说明这个区间没有元素直接返回null
if (left > right) return null;
// 计算中间节点的索引
const mid = left + Math.floor((right - left) / 2);
// 创建根节点,或子树的根节点
const root = new TreeNode(nums[mid]);
// 递归处理左半部分和右半部分
root.left = f1(left, mid - 1, nums);
root.right = f1(mid + 1, right, nums);
return root;
}