
树是由一些边连接的节点的集合。按照惯例,树的每个节点 保存一些数据和对其子节点的引用。
二叉搜索树是一棵二叉树,其中具有较小值的节点存储在左侧,而具有较小值的节点存储在左侧。较高的值存储在右侧。
例如,有效 BST 的视觉表示是 -
25 / \ 20 36 / \ / \ 10 22 30 40
现在让我们用 JavaScript 语言实现我们自己的二叉搜索树。
该类将表示存在于 BST 中各个点的单个节点。 BST 没什么 而是按照规则放置的存储数据和子引用的节点的集合 如上所述。
class Node{
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
};
};要创建一个新的 Node 实例,我们可以使用一些数据来调用此类 -
立即学习“Java免费学习笔记(深入)”;
const newNode = new Node(23);
这将创建一个新的 Node 实例,其数据设置为 23,左右引用均为 null。
class BinarySearchTree{
constructor(){
this.root = null;
};
};这将创建二叉搜索树类,我们可以使用 new 关键字调用它来创建一个 树实例。
现在我们已经完成了基本的工作,让我们继续在正确的位置插入一个新节点(根据定义中描述的 BST 规则)。
class BinarySearchTree{
constructor(){
this.root = null;
}
insert(data){
var newNode = new Node(data);
if(this.root === null){
this.root = newNode;
}else{
this.insertNode(this.root, newNode);
};
};
insertNode(node, newNode){
if(newNode.data < node.data){
if(node.left === null){
node.left = newNode;
}else{
this.insertNode(node.left, newNode);
};
} else {
if(node.right === null){
node.right = newNode;
}else{
this.insertNode(node.right,newNode);
};
};
};
};class Node{
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
};
};
class BinarySearchTree{
constructor(){
this.root = null;
}
insert(data){
var newNode = new Node(data);
if(this.root === null){
this.root = newNode;
}else{
this.insertNode(this.root, newNode);
};
};
insertNode(node, newNode){
if(newNode.data < node.data){
if(node.left === null){
node.left = newNode;
}else{
this.insertNode(node.left, newNode);
};
} else {
if(node.right === null){
node.right = newNode;
}else{
this.insertNode(node.right,newNode);
};
};
};
};
const BST = new BinarySearchTree();
BST.insert(1);
BST.insert(3);
BST.insert(2);以上就是在 JavaScript 中实现二叉搜索树的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号