生成平衡二叉树, 只需要知道节点的数目即可
生成方式采用中序遍历生成, 所以对应的中序遍历结果也是一个递增序列
基本算法思想为对于一个序列 [1, ...., n]对应的二叉树的根节点一定是棋中间节点, 而[1,...mid] mid [mid+1, ... n] 便是最基本的递归单元
class BNode {
constructor(id, left, right) {
this.id = id
this.left = left
this.right = right
}
get child() {
return [this.left, this.right].filter(i => i) || []
}
}
function getBinTree(count) {
// 从[st, ed) 构建二叉树
function buildTree(st, ed) {
if(st===ed) return null
let mid = Math.floor((st + ed + 1) / 2)
if (st === ed - 1) {
return new BNode(st)
}
let left = buildTree(st, mid )
// 注意这里需要mid + 1, 当前节点的id为mid
let right = buildTree(mid + 1, ed)
return new BNode(mid, left, right)
}
return buildTree(0, count)
}
// 返回字符串
function recursion(root) {
let res = []
function dfs(r) {
if (!r) return
dfs(r.left)
res.push(r.id)
dfs(r.right)
}
dfs(root)
return res
}
let root = getBinTree(100)
let res = recursion(root)
console.log(res.length)
console.log(res.join(','))
来源:oschina
链接:https://my.oschina.net/ahaoboy/blog/3161261