代码如下:
class Node {
constructor(data){
this.left = null
this.right = null
this.value = data
}
}
class BinarySearchTree {
// class BST {
constructor() {
this.root = null;
}
insertNode(root, newNode){
if(newNode.value < root.value){
(!root.left) ? root.left = newNode : this.insertNode(root.left, newNode)
} else {
(!root.right) ? root.right = newNode : this.insertNode(root.right, newNode)
}
}
insert(value) {
let newNode = new Node(value)
if(!this.root){
this.root = newNode
} else {
this.insertNode(this.root, newNode)
}
}
removeNode(root, value){
if(!root){
return null
}
if(value < root.value){
root.left = this.removeNode(root.left, value)
return root
} else if(value > root.value){
root.right = this.removeNode(root.right, value)
return root
} else {
if(!root.left && !root.right){
root = null
return root
}
else if(root.left && !root.right){
root = root.left
return root
}
else if(!root.left && root.right){
root = root.right
return root
}
let minRight = this.findMinNode(root.right)
root.value = minRight.value
root.right = this.removeNode(root.right, minRight.value)
return root
}
}
remove(value){
if(this.root){
this.removeNode(this.root, value)
}
}
findMinNode(root) {
if(!root.left){
return root
} else {
return this.findMinNode(root.left)
}
}
searchNode(root, value) {
if(!root){
return null
}
if(value < root.value){
return this.searchNode(root.left, value)
} else if(value > root.value){
return this.searchNode(root.right, value)
}
return root
}
search(value){
if(!this.root){
return false
}
return Boolean(this.searchNode(this.root, value))
}
preOrder(root){
if(root){
console.log(root.value)
this.preOrder(root.left)
this.preOrder(root.right)
}
}
inOrder(root){
if(root){
this.inOrder(root.left)
this.inOrder(root.right)
}
}
postOrder(root){
if(root){
this.postOrder(root.left)
this.postOrder(root.right)
}
}
}
let BTS = new BinarySearchTree()
BTS.insert(9)
BTS.insert(7)
BTS.insert(23)
console.log(BTS)
// BinarySearchTree {
// root: Node {
// left: Node { left: null, right: null, value: 7 },
// right: Node { left: null, right: null, value: 23 },
// value: 9
// }
//}