您好,欢迎访问一九零五行业门户网

在 JavaScript 中实现二叉搜索树

树数据结构树是由一些边连接的节点的集合。按照惯例,树的每个节点保存一些数据和对其子节点的引用。
二叉搜索树二叉搜索树是一棵二叉树,其中具有较小值的节点存储在左侧,而具有较小值的节点存储在左侧。较高的值存储在右侧。
例如,有效 bst 的视觉表示是 -
25 / \ 20 36 / \ / \10 22 30 40
现在让我们用 javascript 语言实现我们自己的二叉搜索树。
第 1 步:节点类该类将表示存在于 bst 中各个点的单个节点。 bst 没什么而是按照规则放置的存储数据和子引用的节点的集合如上所述。
class node{ constructor(data) { this.data = data; this.left = null; this.right = null; };};
要创建一个新的 node 实例,我们可以使用一些数据来调用此类 -
const newnode = new node(23);
这将创建一个新的 node 实例,其数据设置为 23,左右引用均为 null。
第 2 步:二叉搜索树类:class binarysearchtree{ constructor(){ this.root = null; };};
这将创建二叉搜索树类,我们可以使用 new 关键字调用它来创建一个树实例。
现在我们已经完成了基本的工作,让我们继续在正确的位置插入一个新节点(根据定义中描述的 bst 规则)。
步骤3:在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 中实现二叉搜索树的详细内容。
其它类似信息

推荐信息