二叉树中节点的顺序插入(JS实现)

模拟过程

《二叉树中节点的顺序插入(JS实现)》 二叉树

  1. 插入根节点A
  2. 在父节点A的左下方插入子节点B
  3. 在父节点A的右下方插入子节点C
  4. 在父节点B的左下方插入子节点D
  5. 在父节点B的右下方插入子节点E
  6. 在父节点C的左下方插入子节点F

分析过程

每次插入节点需明确被插入的父节点以及被插入的位置(左右)

明确被插入的父节点

第1步中,需将A存储,因为A在第2,3步中被取出,作为插入操作的父节点
第2步中,需将B存储,因为B在第4,5步中被取出,作为插入操作的父节点
第3步中,需将C存储,因为C在第6步中被取出,作为插入操作的父节点,与此同时,A在被执行右下方的插入操作后,A不能再被插入子节点

第5步中,需将E存储,其在后续的操作中会被取出,作为插入操作的父节点,与此同时,B与A一样,在被执行右下方的插入操作后,B不能再被插入子节点
建个队列,将后续操作中会被取出的节点存储,不会再被取出的节点移除。每次插入的新节点都会入列。同时,若新节点被插入到父节点的右下方,则该父节点出列。

明确被插入的位置

被插入的位置可以通过插入的次数来判断,若是第1次插入,则是根节点,若是第n(n>1)次插入,n为偶,则插入左边,n为奇,则插入右边
故用个变量存储插入的次数

代码

运行环境node v8.4

function Node(value) {
  this.value = value
  this.left = null
  this.right = null
}

function BinaryTree() {
  this.root = null // 树根
  this.queue = [] // 存储会被使用的父节点
  this.insertNum = 0 // 记录插入操作的次数
}

BinaryTree.prototype.insert = function (value) {
  this.insertNum++ // 插入次数加1
    let node = new Node(value)
  if (!this.root) { // 判断根节点是否存在
    this.root = node // 插入根节点
    this.queue.push(this.root) // 新节点入列
  } else { // 插入非根节点
    let parent = this.queue[0] // 被插入的父节点
    if (!(this.insertNum % 2)) { // 通过插入次数判断左右
      parent.left = node // 插入左边
      this.queue.push(parent.left) // 新节点入列
    } else {
      parent.right = node // 插入右边
      this.queue.push(parent.right) // 新节点入列
      this.queue.shift() // 当前父节点parent 已经不可能再插入子节点,故出列
    }
  }
  return this
}

let binaryTree = new BinaryTree()
binaryTree.insert('A')
  .insert('B')
  .insert('C')
  .insert('D')
  .insert('E')
  .insert('F')

console.log(JSON.stringify(binaryTree.root, null, 4))

《二叉树中节点的顺序插入(JS实现)》 output.png

插入空节点

《二叉树中节点的顺序插入(JS实现)》 插入空节点.png

首先需要判断插入的节点是否为空节点
若是空节点,其不会作为父节点被执行插入操作,故不用入列

改进代码

BinaryTree.prototype.insert = function (value) {
  this.insertNum++ // 插入次数加1
    let node = (!value && typeof value === 'object') ? null : new Node(value) // 判断是否为空节点

  if (!this.root) { // 判断根节点是否存在
    this.root = node // 插入根节点
    node && this.queue.push(this.root) // 非空节点入列
  } else { // 插入非根节点
    let parent = this.queue[0] // 被插入的父节点
    if (!(this.insertNum % 2)) { // 通过插入次数判断左右
      parent.left = node // 插入左边
      node && this.queue.push(parent.left) // 非空节点入列
    } else {
      parent.right = node // 插入右边
      node && this.queue.push(parent.right) // 非空节点入列
      this.queue.shift() // 当前父节点parent 已经不可能再插入子节点,故出列
    }
  }
  return this
}

let binaryTree = new BinaryTree()
binaryTree.insert('A')
  .insert('B')
  .insert('C')
  .insert('D')
  .insert('E')
  .insert(null)
  .insert('F')
  .insert('G')

console.log(JSON.stringify(binaryTree.root, null, 4))

《二叉树中节点的顺序插入(JS实现)》 output2.png

    原文作者:nbb3210
    原文地址: https://www.jianshu.com/p/dc04871eab51
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞