Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

108.将有序数组转换为二叉搜索树 #7

Open
funnycoderstar opened this issue Aug 22, 2018 · 0 comments
Open

108.将有序数组转换为二叉搜索树 #7

funnycoderstar opened this issue Aug 22, 2018 · 0 comments

Comments

@funnycoderstar
Copy link
Owner

funnycoderstar commented Aug 22, 2018

JavaScript实现LeetCode第108题:将有序数组转换为二叉搜索树

题目描述

将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。

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

示例:

给定有序数组: [-10,-3,0,5,9],

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

      0
     / \
   -3   9
   /   /
 -10  5

思路

1.如果nums长度为0,返回null
2.如果nums长度为1,返回一个节点
3.如果nums长度大于1,首先以中点作为根节点,然后将两边的数组作为左右子树。

解决方案

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {number[]} nums
 * @return {TreeNode}
 */
var sortedArrayToBST = function(nums) {
    if(nums.length === 0) {
        return null;
    }
    if(nums.length === 1) {
        return new TreeNode(nums[0]);
    }
    const mid = parseInt(nums.length / 2);
    let root = new TreeNode(nums[mid]);
    root.left = sortedArrayToBST(nums.slice(0, mid));
    root.right = sortedArrayToBST(nums.slice(mid + 1));
    return root;
};
@funnycoderstar funnycoderstar changed the title 108.将有序数组转换为二叉搜索树(JavaScript) 108.将有序数组转换为二叉搜索树 Aug 22, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant