二叉树的顺序插入

发布时间:2019-06-08 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了二叉树的顺序插入脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

模拟过程@H_304_2@

二叉树

  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))

output.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))

二叉树的顺序插入

脚本宝典总结

以上是脚本宝典为你收集整理的二叉树的顺序插入全部内容,希望文章能够帮你解决二叉树的顺序插入所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。