构造二叉树

116 阅读1分钟

为什么经典算法是二叉树不是三叉树四叉树

因为二分法

构造二叉树

  • 父级规律 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
  }
}