题目
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
讲一个升序的数组,转换为一个BST(搜索二叉树)
- Example
Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
思路
- 通过中序遍历得到的二叉搜索树就是一个升序的数组(左-根-右)
- 反过来思考,中间点肯定就是二叉树的根节点
所以获取中间值nums[mid]为根节点root,root.left又是[0,mid]的中间值
同理root.right是[mid,nums.lenght]的中间值
然后采用递归即可得到
解法
var sortedArrayToBST = function(nums){
if(!nums.length) return null
var mid = Math.floor(nums.length/2)
var root = new TreeNode(nums[mid])
root.left = sortedArrayToBST(nums.slice(0,mid))
root.right = sortedArrayToBST(nums.slice(mid+1))
return node
}
按照上面例子就是
1 queue = [3]
2 node = 3, level = [3], queue = []
3 node.left = 9, node.right = 20, queue = [9,20]
下一轮循环
1 queue = [9,20]
2 node = 9,level = [9],queue = [20]
3 node = 20,level = [9,20], queue = []
4 node.left = 15, node.right = 7,queue = [17,7]
再一次下一轮。。。
网友评论