class Node {
constructor(data) {
this.left = null
this.right = null;
this.data = data;
}
}
class Tree {
constructor() {
this.root = null;
}
//插入
insert(data) {
const insertNode = (node, data) => {
if (node.data > data) {
if (node.left) {
insertNode(node.left, data)
} else { node.left = new Node(data) }
} else if (node.data < data) {
if (node.right) {
insertNode(node.right, data)
} else {
node.right = new Node(data)
}
}
}
if (this.root == null) { this.root = new Node(data) }
insertNode(this.root, data)
}
//删除
remove(data) {
var self = this;
const rm = (node, data) => {
if (node === null) return null;
if (data === node.data) {
if (node.left === null && node.right === null) {
return null;
} else if (node.left === null) {
return node.right;
} else if (node.right === null) {
return node.left;
} else {
var minNode = self.getMin(node.right)
node.data = minNode.data;
node.right = rm(node.right, node.data);
return node;
}
} else {
if (data < node.data) {
node.left = rm(node.left, data);
} else if (data > node.data) {
node.right = rm(node.right, data);
}
return node;
}
}
this.root = rm(this.root, data);
return true
}
//前序遍历
prevTree() {
const toString = function (node) {
if (node) {
console.log(node.data)
toString(node.left)
toString(node.right)
}
}
toString(this.root)
}
//中序遍历
middleTree() {
const toString = function (node) {
if (node) {
toString(node.left)
console.log(node.data)
toString(node.right)
}
}
toString(this.root)
}
//后序遍历
behindTree() {
const toString = function (node) {
if (node) {
toString(node.left)
toString(node.right)
console.log(node.data)
}
}
toString(this.root)
}
//获取最大值
getMax() {
const maxNode = (node) => {
let current = node;
while (current != null && current.right != null) {
current = current.right ? current.right : current
}
return current
}
var x = maxNode(this.root)
return x;
}
//获取最小值
getMin(y) {
const minNode = (node) => {
let current = node;
while (current != null && current.left != null) {
current = current.left ? current.left : current
}
return current
}
var x = minNode(y)
return x;
}
}