每次插入节点需明确被插入的父节点以及被插入的位置(左右)node
第1步中,需将A存储,由于A在第2,3步中被取出,做为插入操做的父节点
第2步中,需将B存储,由于B在第4,5步中被取出,做为插入操做的父节点
第3步中,需将C存储,由于C在第6步中被取出,做为插入操做的父节点,与此同时,A在被执行右下方的插入操做后,A不能再被插入子节点
...
第5步中,需将E存储,其在后续的操做中会被取出,做为插入操做的父节点,与此同时,B与A同样,在被执行右下方的插入操做后,B不能再被插入子节点
故建个队列,将后续操做中会被取出的节点存储,不会再被取出的节点移除。每次插入的新节点都会入列。同时,若新节点被插入到父节点的右下方,则该父节点出列。this
被插入的位置能够经过插入的次数来判断,如果第1次插入,则是根节点,如果第n(n>1)次插入,n为偶,则插入左边,n为奇,则插入右边
故用个变量存储插入的次数spa
运行环境node v8.4prototype
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))
首先须要判断插入的节点是否为空节点
如果空节点,其不会做为父节点被执行插入操做,故不用入列3d
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))