为什么经典算法是二叉树不是三叉树四叉树
因为二分法
构造二叉树
- 父级规律 const n = parseInt((i - 1) / 2) (i>0)
class Node {
constructor(val) {
this.val = val
this.left = this.right = undefined
}
}
class Tree {
constructor(data) {
let nodeList = []
let root
for (let i = 0; i < data.length; i++) {
let node = new Node(data[i])
nodeList.push(node)
if (i > 0) {
const n = parseInt((i - 1) / 2)
const parent = nodeList[n]
if (parent.left) {
parent.right = node
} else {
parent.left = node
}
}
}
root = nodeList.shift()
nodeList.length = 0
return root
}
}