Open Genzhen opened 3 years ago
使用递归求解,时间复杂度O(n), 空间复杂度O(n)
function TreeNode(val, left = null, right = null) {
this.val = val
this.left = left
this.right = right
}
// 转化为二分搜索树
function buildBST(arr = []) {
return _buildBST(arr, 0, arr.length - 1)
}
function _buildBST(arr = [], left, right) {
const len = right - left + 1
console.log(left, right)
// 临界条件判断,只有一个节点
if (left === right) {
return new TreeNode(arr[left])
} else if (left > right) {
return null
}
const mid = Math.floor(left + (right - left) / 2)
const root = new TreeNode(arr[mid])
root.left = _buildBST(arr, left, mid - 1)
root.right = _buildBST(arr, mid + 1, right)
return root
}
扫描下方二维码,收藏关注,及时获取答案以及详细解析,同时可解锁800+道前端面试题。