Javascript实现二叉搜索树
来源:互联网 发布:图片上传到淘宝变模糊 编辑:程序博客网 时间:2024/06/02 04:18
class Node { //节点结构 constructor(data, left, right) { this.data = data; this.left = left; this.right = right; }}class BinarySearchTree { //二叉树、添加节点、删除节点、查询节点 constructor() { this.root = null; } insert(data) { let n = new Node(data, null, null); if (!this.root) { return this.root = n; } let currentNode = this.root; let parent = null; while (1) { parent = currentNode; if (data < currentNode.data) { currentNode = currentNode.left; if (currentNode === null) { parent.left = n; break; } } else { currentNode = currentNode.right; if (currentNode === null) { parent.right = n; break; } } } } remove(data) { this.root = this.removeNode(this.root, data) } removeNode(node, data) { if (node == null) { return null; } if (data == node.data) { // no children node if (node.left == null && node.right == null) { return null; } if (node.left == null) { return node.right; } if (node.right == null) { return node.left; } let getSmallest = function(node) { if(node.left === null && node.right == null) { return node; } if(node.left != null) { return node.left; } if(node.right !== null) { return getSmallest(node.right); } } let temNode = getSmallest(node.right); node.data = temNode.data; node.right = this.removeNode(temNode.right,temNode.data); return node; } else if (data < node.data) { node.left = this.removeNode(node.left,data); return node; } else { node.right = this.removeNode(node.right,data); return node; } } find(data) { var current = this.root; while (current != null) { if (data == current.data) { break; } if (data < current.data) { current = current.left; } else { current = current.right } } return current.data; }}module.exports = BinarySearchTree;
阅读全文
0 0
- Javascript实现二叉搜索树
- Javascript二叉搜索树实现
- javascript:二叉搜索树的实现
- javascript 搜索二叉树
- Javascript实现从小到大的数组转换成二叉搜索树
- 最大堆、索引堆、二叉搜索树的JavaScript实现
- 二叉搜索树实现
- 搜索二叉树实现
- 搜索二叉树实现
- 二叉搜索树实现
- 二叉树 javascript实现
- JavaScript实现二叉树
- 二叉搜索树的实现
- 二叉搜索树C++实现
- 实现一个搜索二叉树
- java实现二叉搜索树
- 二叉搜索树的实现
- 二叉搜索树的实现
- LeetCode (Unique Binary Search Trees)
- 编译原理:素短语、短语、直接短语、句柄的基本概念
- Jenkins初识
- A. Vladik and Courtesy
- 搬运工整理之 HoloLens 开发环境搭建 01
- Javascript实现二叉搜索树
- 输入输出练习
- Date对象
- java时间格式转换
- JNDI
- class文件结构
- JAVA-JDBC: (2) 数据库的粗略的CRUD及SQL注入问题
- 基于opencv31 下的KCF 跟踪在windows 下的测试
- Dom对象