二叉搜索树(Binary Search Tree)指左子树的值小于根节点的值,右子树的值大于根节点的值。
BTS 基本结构:
function Node(val) {
this.val = val;
this.left = null;
this.right = null;
}
function Tree() {
this.root = null;
}
Tree.prototype = {
insert,
getMin,
getMax,
getDeep,
};
BTS 插入数据:
function insert(val) {
this.root = insertNode(this.root, val);
function insertNode(root, val) {
if (!root) {
return new Node(val);
}
if (val < root.val) {
root.left = insertNode(root.left, val);
} else if (val > root.val) {
root.right = insertNode(root.right, val);
}
return root;
}
}
查找最大最小值:
function getMax() {
let current = this.root;
while (current) {
if (!current.right) {
return current;
}
current = current.right;
}
}
function getMin() {
let current = this.root;
while (current) {
if (!current.left) {
return current;
}
current = current.left;
}
}
获取树的深度
function getDeep(node, deep) {
deep = deep || 0;
if (node === null) {
return deep;
}
deep++;
let dleft = this.getDeep(node.left, deep);
let dright = this.getDeep(node.right, deep);
return Math.max(dleft, dright);
}
前序遍历:
function preOrder(node) {
const stack = [];
while (node || stack.length) {
while (node) {
console.log(node.val);
stack.push(node); // stack 储存父节点
node = node.left; // 去找左儿子
}
node = stack.pop();
node = node.right; // 去找右儿子
}
}
中序遍历:
function inOrder(node) {
let stack = [];
while (stack.length || node) {
while (node) {
stack.push(node);
node = node.left;
}
node = stack.pop();
console.log(node.val);
node = node.right;
}
}
后序遍历:
function postOrder(node) {
const stack = [];
let cur = node;
let last = null;
while (cur || stack.length) {
while (cur) {
stack.push(cur);
cur = cur.left;
}
cur = stack[stack.length - 1];
if (!cur.right || cur.right === last) {
cur = stack.pop();
console.log(cur.val);
last = cur;
cur = null;
} else {
cur = cur.right;
}
}
}