function BinarySearchTree() {
this.root = null;
function Node(key) {
this.key = key;
this.left = null;
this.right = null;
}
//插入节点
BinarySearchTree.prototype.insert = function (key) {
var node = new Node(key);
if (this.root == null) {
this.root = node;
} else {
this.insertNode(this.root, node);
}
};
//递归寻找合适的位置插入
BinarySearchTree.prototype.insertNode = function (root, node) {
if (root.key > node.key) {
if (root.left == null) {
root.left = node;
} else {
this.insertNode(root.left, node);
}
} else {
if (root.right == null) {
root.right = node;
} else {
this.insertNode(root.right, node);
}
}
};
//先序遍历
BinarySearchTree.prototype.preOrderTraversal = function (fn) {
this.preOrderTraversalNode(this.root, fn);
};
js手写二叉搜索树
最新推荐文章于 2022-04-19 09:24:07 发布