We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定有序数组: [-10,-3,0,5,9], 一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树: 0 / \ -3 9 / / -10 5
解法:
有序数组取数组的中间元素作为结点, 将数组分成左右两部分,对数组的两部分用递归的方法分别构建左右子树。
/** * 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) { let sort=(left, right)=>{ if(left > right){ return null; } // console.log(` ${left} ${right}`); var m = left + Math.floor((right-left)/2); //取中间值 递归排序 var node = new TreeNode(nums[m]); node.left = sort(left, m-1); node.right = sort(m+1, right); return node; } return sort(0, nums.length-1); };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
解法:
有序数组取数组的中间元素作为结点, 将数组分成左右两部分,对数组的两部分用递归的方法分别构建左右子树。
The text was updated successfully, but these errors were encountered: