哇啊!!写删除拥有两个子节点的树的时候真让我感概人类智力竟如此璀璨啊!!!真的太妙了,妙不可言,本来毫无思路简直想死,结果突然开窍的感觉太妙了!!!
'use strict';
class Node {
constructor (key) {
this.key = key
this.left = null
this.right = null
}
}
class binarySearchTree {
// 构造函数
constructor () {
this.node = new Node()
this.root = null
}
// insert的子方法
// 用于不停递归,而后求出插入节点的位置并插入节点
// 依次入栈,逐次出栈
insertNode (root, node) {
if (node.key < root.key) {
root.left === null ? root.left = node : this.insertNode(root.left, node)
} else {
root.right === null ? root.right = node : this.insertNode(root.right, node)
}
}
// 插入新节点
insert (key) {
let node = new Node(key)
if (this.root === null) {
this.root = node
} else {
this.insertNode(this.root, node)
}
}
searchChild (node, key) {
if (node === null) {
return false
} else if (key < node.key) {
return this.searchChild(node.left, key)
} else if (key > node.key) {
return this.searchChild(node.right, key)
} else {
return true
}
}
search (key) {
return this.searchChild(this.root, key)
}
// 中序遍历
// 从最左开始逐列遍历
// 即从小到大排列
inOrderTraverse (node) {
if (node !== null) {
this.inOrderTraverse(node.left)
console.log(node.key);
this.inOrderTraverse(node.right)
}
}
// 先序遍历
preOrderTraverse (node) {
if (node !== null) {
console.log(node.key);
this.preOrderTraverse(node.left)
this.preOrderTraverse(node.right)
}
}
// 后序遍历
postOrderTraverse (node) {
if (node !== null) {
this.postOrderTraverse(node.left)
this.postOrderTraverse(node.right)
console.log(node.key);
}
}
// 返回树中最小值
min () {
let node = this.root
while (node.left) {
node = node.left
}
console.log("MIN: " + node.key);
return true
}
// 返回树中最大值
max () {
let node = this.root
while (node.right) {
node = node.right
}
console.log("MAX: " + node.key);
return true
}
removeChild (node, key) {
if (node === null) {
return false
}
if (key < node.key) {
node.left = this.removeChild(node.left, key)
return node
} else if (key > node.key) {
node.right = this.removeChild(node.right, key)
return node
} else {
// 即node.key === key
if (node.left === null || node.right === null) {
node = null
return node
} else if (node.left === null) {
node = node.right
return node
} else if (node.right === null) {
node.right = node.left
return node
} else {
// 即两边皆存在节点
// 从右侧取最小大值最为node.key
let temp = node.right;
while (temp.left) {
temp = temp.left
}
node.key = temp.key
node.right = this.removeChild(node.right, temp.key)
return node
}
}
}
// 移除
remove (key) {
this.root = this.removeChild(this.root, key)
}
}
// 测试
let tree = new binarySearchTree()
tree.insert(11)
tree.insert(7)
tree.insert(15)
tree.insert(5)
tree.insert(3)
tree.insert(9)
tree.insert(8)
tree.insert(10)
tree.insert(13)
tree.insert(12)
tree.insert(14)
tree.insert(20)
tree.insert(18)
tree.insert(25)
tree.insert(6)
tree.inOrderTraverse(tree.root);
console.log('=====');
tree.preOrderTraverse(tree.root);
console.log('=====');
tree.postOrderTraverse(tree.root);
tree.max();
tree.min()
console.log(tree.search(5));
tree.remove(11)
console.log('===当前值为===');
tree.inOrderTraverse(tree.root);
网友评论