返回
从蛋壳破裂到展翅高飞:JS 数据结构和算法实现——二分搜索树(一)
前端
2024-02-04 02:19:43
正文
二分搜索树(BST),是计算机科学中一种重要的非线性数据结构,它由结点组成,每个结点包含一个数据项和两个指针,分别指向其左子树和右子树。BST 的主要特征是:
- 每个结点的数据项都大于其左子树的所有结点的数据项,而小于其右子树的所有结点的数据项。
- 左子树和右子树也都是二分搜索树。
BST 的主要优点在于查找效率高,在最坏的情况下,查找一个元素的时间复杂度为 O(log n),其中 n 是树中的结点数。
一、创建二分搜索树
在 JavaScript 中,我们可以使用以下代码来创建一个二分搜索树:
function BSTNode(data) {
this.data = data;
this.left = null;
this.right = null;
}
function BST() {
this.root = null;
this.insert = function(data) {
var newNode = new BSTNode(data);
if (this.root === null) {
this.root = newNode;
} else {
this.insertNode(newNode, this.root);
}
};
this.insertNode = function(newNode, node) {
if (newNode.data < node.data) {
if (node.left === null) {
node.left = newNode;
} else {
this.insertNode(newNode, node.left);
}
} else {
if (node.right === null) {
node.right = newNode;
} else {
this.insertNode(newNode, node.right);
}
}
};
}
二、二分搜索树的遍历
BST 的遍历方法主要有三种:前序遍历、中序遍历和后序遍历。
- 前序遍历:先访问根结点,然后访问左子树,最后访问右子树。
- 中序遍历:先访问左子树,然后访问根结点,最后访问右子树。
- 后序遍历:先访问左子树,然后访问右子树,最后访问根结点。
这三种遍历方法的实现代码如下:
this.preOrder = function(node) {
if (node !== null) {
console.log(node.data);
this.preOrder(node.left);
this.preOrder(node.right);
}
};
this.inOrder = function(node) {
if (node !== null) {
this.inOrder(node.left);
console.log(node.data);
this.inOrder(node.right);
}
};
this.postOrder = function(node) {
if (node !== null) {
this.postOrder(node.left);
this.postOrder(node.right);
console.log(node.data);
}
};
三、二分搜索树的时间复杂度分析
BST 的时间复杂度主要由以下几个因素决定:
- 树的高度:树的高度是指从根结点到最远叶结点的路径长度。树的高度越高,查找效率就越低。
- 树的平衡性:树的平衡性是指树的左右子树的高度差。树的平衡性越好,查找效率就越高。
- 数据分布:数据分布是指数据在树中的分布情况。如果数据分布均匀,查找效率就越高。
在最坏的情况下,BST 的查找时间复杂度为 O(n),其中 n 是树中的结点数。在最好情况下,BST 的查找时间复杂度为 O(log n)。
结语
二分搜索树是一种非常高效的数据结构,它广泛应用于各种领域。在本文中,我们介绍了二分搜索树的基础概念、创建、遍历和时间复杂度分析。希望这篇文章对您有所帮助。