class BinarySearchTree {
constructor() {
// 节点类
class Node {
constructor(key) {
this.key = key;
this.left = null;
this.right = null;
}
}
// 二叉搜索树的根
this.root = null;
// 1.插入数据
BinarySearchTree.prototype.insert = function (key) {
var newNode = new Node(key);
// 判断有无根节点
if (this.root == null) this.root = newNode;
else {
//递归查询
this.insertNode(this.root, newNode)
}
}
// 将已有的节点和新节点进行比较
BinarySearchTree.prototype.insertNode = function (node, newNode) {
// 如果新插入节点比原节点小,则向左查找
if (newNode.key < node.key) {
//如果node的左子树为空,则将newnode作为node的左子树存储起来
if (node.left == null) node.left = newNode;
// 否则将继续递归
else {
this.insertNode(node.left, newNode)
}
}
//如果新插入的节点比原节点大,则向右查找
else {
// 如果node的右子树为空,则将newnode作为node的右子树
if (
JavaScript实现二叉搜索树结构以及部分方法的封装
最新推荐文章于 2021-09-21 10:58:35 发布