二叉树
// 创建节点
function Node(data, left, right) {
this.data = data
this.left = left
this.right = right
this.show = () => this.data
}
// 二叉查找树
function BST() {
this.root = null
this.insert = function (data) {
let node = new Node(data, null, null);
// 如果 BST.root === null ,那么就将节点作为根节点
// 如果 BST.root !== null ,将插入节点进行一个比较,小于根节点,拿到左边的节点,否则拿右边,再次比较、递归。
if (this.root === null) {
this.root = node
} else {
let current = this.root;
let parent;
while (true) {
parent = current;
if (data < current.data) {
current = current.left; // 到左子树
if (current === null) {
// 如果左子树为空,说明可以将node插入在这里
parent.left = node;
break; // 跳出while循环
}
} else {
current = current.right;
if (current === null) {
parent.right = node;
break;
}
}
}
}
}
// 中序
this.inOrder = function () {
const arr = []
const _inOrder = (node) => {
if (node !== null) {
//如果不是null,就一直查找左变,因此递归
_inOrder(node.left);
//递归结束,打印当前值
arr.push(node.show())
//上一次递归已经把左边搞完了,右边
_inOrder(node.right);
}
}
_inOrder(this.root)
return arr
}
// 前序
this.preOrder = function () {
const arr = []
const _preOrder = (node) => {