JS二叉树的实现及前序遍历、中序遍历、后序遍历
// 二叉树的实现
function Node(data, left, right) {
this.data = data;
this.left = left;
this.right = right;
this.show = () => {
return this.data;
};
}
function BST() {
this.root = null;
this.insert = insert; // 插入节点方法
this.preOrder = preOrder;
this.inOrder = inOrder;
this.postOrder = postOrder;
}
function insert(n) {
let node = new Node(n, null, null);
if (this.root === null) {
this.root = node;
} else {
let current = this.root;
while (true) {
if (n < current.data) {
if (current.left == null) {
current.left = node;
break;
}
current = current.left;
} else {
if (current.right == null) {
current.right = node;
break;
}
current = current.right;
}
}
}
}
var bst = new BST();
var nums = [10, 3, 18, 2, 4, 13, 21, 9, 8, 9];
for (var i = 0; i < nums.length; i++) {
bst.insert(nums[i]);
}
console.log("树结构", bst);
bst.preOrder(bst.root);
// bst.inOrder(bst.root);
// bst.postOrder(bst.root);
// 前序遍历:父节点 -> 左节点 -> 右节点
function preOrder(node) {
if (node !== null) {
console.log(node.show() + " ");
preOrder(node.left);
preOrder(node.right);
}
}
// 10 -> 3 -> 2 -> 4 -> 9 -> 8 -> 9 -> 18 -> 13 -> 21
// 中序遍历:左节点 -> 父节点 -> 右节点
function inOrder() {
if (node !== null) {
inOrder(node.left);
console.log(node.show() + " ");
inOrder(node.right);
}
}
// 2 -> 3 -> 4 -> 8 -> 9 -> 9 -> 10 -> 13 -> 18 -> 21
// 后序遍历:左节点 -> 右节点 -> 父节点
function postOrder() {
if (node !== null) {
postOrder(node.left);
postOrder(node.right);
console.log(node.show() + " ");
}
}
// 2 -> 8 -> 9 -> 9 -> 4 -> 3 -> 13 -> 21 -> 18 -> 10