search
HomeWeb Front-endJS TutorialDetailed explanation of using JS binary search tree

Detailed explanation of using JS binary search tree

Apr 18, 2018 am 09:36 AM
javascriptuseDetailed explanation

This time I will bring you a detailed explanation of the use of JS binary search trees. What are the precautions when using JS binary search trees? The following is a practical case. Get up and take a look.

What is a binary tree

A binary tree means that each node of the tree can only have at most two child nodes

What is a binary search tree

On the basis of the binary tree, the binary search tree has an additional condition, that is, when inserting a value in the binary tree, if the inserted value is smaller than the current node, it will be inserted into the left node, otherwise it will be inserted into the right node; if during the insertion process, the left node or If the right node already exists, then continue to compare according to the above rules until a new node is encountered.

Characteristics of binary search trees

Due to its unique data structure, the binary search tree has a time complexity of O(h) whether it is adding, deleting or searching. h is the height of the binary tree. Therefore, the binary tree should be as short as possible, that is, the left and right nodes should be as balanced as possible.

Construction of binary search tree

To construct a binary search tree, you must first construct the node class of the binary tree. It can be seen from the characteristics of binary trees that each node class has a left node, a right node and the value itself, so the node class is as follows:

class Node {
 constructor(key) {
  this.key = key;
  this.left = null;
  this.right = null;
 }
}

Then construct a binary search tree

class Tree{
 constructor(param = null) {
  if (param) {
   this.root = new Node(param);
  } else {
   this.root = null;
  }
 }
}

Here this.root is the tree of the current object.

Binary search treeNew addition

Due to the characteristics of the binary search tree that the left subtree is smaller than the node and the right subtree is larger than the node, the new algorithm for the binary search tree can be easily written, as follows:

insert(key) {
 if (this.root === null) {
  this.root = new Node(key);
 } else {
  this._insertNode(this.root, key);
 }
}
_insertNode(node, key) {
 if (key  node.key) {
  if (node.right === null) {
   node.right = new Node(key);{3}
  } else {
   this._insertNode(node.right, key);{4}
  }
 }
}

The above code first determines the key size of the newly added key and the current node. If it is smaller, it recursively traverses the left child node until it finds a null left child node; if it is larger than the current node, the same principle applies. The reason why the above code {1}{2}{3}{4} can change the value of this.root is because the JavaScript function is passed by value, and when the parameter is a non-basic type, such as here Object, the value of its object is memory, so the content of this.root will be directly changed every time.

Traversal of binary search tree

Binary search trees are divided into three traversal methods: preorder, inorder, and postorder.

inOrderTraverse(callback) {
 this._inOrderTraverse(this.root, callback);
}
_inOrderTraverse(node, callback) {
 if (node) {
  this._inOrderTraverse(node.left, callback);
  callback(node.key);
  this._inOrderTraverse(node.right, callback);
 }
}

The above is an in-order traversal.

The thing to understand here is recursion. You know, the execution of a function can be abstracted into a data structure - a stack. For the execution of the function, a stack is maintained to store the execution of the function. Each time the function recurses, it will push the current execution environment onto the stack and record the execution location. Taking the above code as an example, there is the following data

It will start from 11, execute {1} to the stack, then go to 7, then execute {1} to the stack, then go to 5, execute {1} to the stack, and then go to 3, execute {1} to the stack. At this time, it is found that The left child node of node 3 is null, so it starts to pop off the stack. At this time, the execution environment of node 3 pops up, execute {2}, {3}, and find that the right child node of 3 is also null, and the recursive execution of {3} is completed. , then pop up node 5, execute {2}{3}, then pop up node 7, execute {2}{3} onto the stack, when executing {3}, it is found that node 7 has a right node, so continue executing {1}, to the node 8, execute {1} again, 8 has no left child node, {1} is executed, {2}{3} is executed, and so on.

The difference between preorder and midorder is that the node itself is visited first, that is, the execution order of the code is 2 1 3.

The same applies to the post-order, the execution order is 1 3 2

It is not difficult to find that no matter the order is before, during or after, the left node is always recursed first. When the left node is traversed, the stack is popped and all nodes are traversed. The only difference between them is the timing of accessing the node itself.

Binary search tree search

The search is very simple, just make a loop judgment based on the principle that the left child node is smaller than the node and the right child node is larger than the node.

search(value) {
 if (this.root) {
  if (value === this.root.key) {
   return true;
  } else {
   return this._searchNode(value, this.root);
  }
 }
 throw new Error('this.root 不存在');
}
_searchNode(value, node) {
 if (!node) {
  return false;
 }
 if (value === node.key) {
  return true;
 }
 if (value > node.key) {
  return this._searchNode(value, node.right);
 } else if (value <p style="text-align: left;">
<strong>Binary search tree<a href="http://www.php.cn/php/php-tp-remove.html" target="_blank">Delete</a></strong></p><p style="text-align: left;">
Deletion is more complicated and needs to be judged according to different situations</p><p style="text-align: left;">
First determine whether the node has a left subtree. If there is no left subtree, directly replace the deleted node with the root node of the right subtree; </p><p style="text-align: left;">
If there is, replace the deleted node with the smallest node of the right subtree;</p><pre class="brush:php;toolbar:false">remove(key) {
 this._removeNode(this.root, key);
}
_removeNode(node, value) {
 if (!node) {
  return null;
 }
 if (value > node.key) {
  node.right = this._removeNode(node.right, value);
 } else if (value <p style="text-align: left;">
	<strong>总结</strong></p><p style="text-align: left;">
	总的来说,通过这次简单的二叉搜索树的学习,让我重新认识了递归,以前对于递归的理解只是一些简单的理论概念,这次深入实践让我对递归的理解又加深了许多。</p><p style="text-align: left;">这让我想到了数学的学习,数学的理论公式是很容易记住掌握的,如果说对一个知识点的掌握满分是十分,那么直到真正去实践它之前,只看公式的掌握只能是2分,因为公式很简单,就几句话几个原则,但是遇到的问题是千变万化的,只有真正将理论付诸实践,经过各种实践的打磨蹂躏,才能真正理解它其中的奥秘。
          </p><p>相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!</p><p>推荐阅读:</p><p><a href="http://www.php.cn/js-tutorial-393137.html" target="_blank">react-native-fs插件使用案列详解</a><br></p><p><a href="http://www.php.cn/js-tutorial-393135.html" target="_blank">js实现字符限制中文汉字=两个字符</a><br></p><p style="text-align: left;"><a href="http://www.php.cn/js-tutorial-393132.html" target="_blank">优化页面加载速度插件InstantClick</a><br></p><!--content end-->

The above is the detailed content of Detailed explanation of using JS binary search tree. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor