Home Web Front-end JS Tutorial Detailed explanation of red-black tree insertion and examples of Javascript implementation methods

Detailed explanation of red-black tree insertion and examples of Javascript implementation methods

May 28, 2018 pm 05:39 PM
javascript js method

This article mainly introduces you to the relevant information about the insertion of red-black trees, as well as the Javascript implementation method. The article introduces it in great detail through sample code. It has certain reference learning value for everyone's study or work. It needs Let’s take a look at it together.

Properties of red-black trees

A binary search tree that satisfies the following properties is a red-black tree

  1. Each node is either black or red.

  2. The root node is black.

  3. Each leaf node (NIL) is black.

  4. If a node is red, both of its child nodes are black.

  5. For each node, the simple path from the node to all its descendant leaf nodes contains the same number of black nodes.

Property 1 and Property 2 don’t need to be explained too much.

Property 3, each leaf node (NIL) is black. The leaf nodes here do not refer to nodes 1, 5, 8, and 15 in the above figure, but to the nodes with null values ​​in the figure below. Their color is black and they are the child nodes of their parent nodes. .

Property 4, if a node is red (white is used instead of red in the figure), then its two child nodes are black, such as node 2 ,5,8,15. However, if both child nodes of a node are black, the node may not be red, such as node 1.

Property 5, for each node, the simple path from the node to all its descendant leaf nodes contains the same number of black nodes. For example, on the simple path from node 2 to all its descendant leaf nodes, the number of black nodes is 2; on the simple path from root node 11 to all its descendant leaf nodes, the number of black nodes is 2. is 3.

What are the characteristics of such a tree?

By constraining the color of each node on any simple path from the root to the leaf node, the red-black tree ensures that no path will be twice as long as any other path. Because it is approximately balanced. ——"Introduction to Algorithms"

Due to property 4, two red nodes will not be adjacent in a red-black tree. The shortest possible path in the tree is the path with all black nodes, and the longest possible path in the tree is the path with alternating red nodes and black nodes. Combined with property 5, each path contains the same number of black nodes, so the red-black tree ensures that no path will be twice as long as other paths.

Insertion of red-black tree

First insert the node in the binary search tree and color it red . If it is black, it will violate property 5 and is inconvenient to adjust; if it is red, it may violate property 2 or property 4. It can be restored to the properties of a red-black tree through relatively simple operations.

After a node is inserted in a binary search tree, the following situations may occur:

Scenario 1

After inserting the node, there is no parent node, and the node is inserted to become the root node, which violates property 2. The node is adjusted to black to complete the insertion.

Case 2

After inserting a node, its parent node is black, and does not violate any properties. No adjustment is required, and the insertion is completed. For example, insert node 13 in the figure below.

Case 3

After inserting a node, its parent node is red, which violates property 4 and requires a series of adjustments. For example, insert node 4 in the figure below.

#So what are the series of adjustments?

If the parent node father of the inserted node node is red, then the node father must have a black parent node grandfather, because if the node father does not have a parent node, it is the root node. point, and the root node is black. Then the other child node of the node grandfather can be called the node uncle, which is the sibling node of the node father. The node uncle may be black or red.

Let’s analyze the simplest situation first, because complex situations can be transformed into simple situations. The simple situation is the situation where the node uncle is black.

Scenario 3.1

As shown in (a) above, the situation is like this, node is red, father is red, grandfather and uncle are black, α , β, θ, ω, and η are all subtrees corresponding to the nodes. Assume that in the entire binary search tree, only node and father cannot become a normal red-black tree due to violation of property 4. At this time, adjusting picture (a) to picture (b) can restore it to a normal red-black tree. The entire adjustment process is actually divided into two steps, rotation and color change.

What is rotation?

The figure (c) above is part of a binary search tree, where x, y are nodes, α, β, θ are subtrees of the corresponding nodes. It can be seen from the figure that α < x < β < y < θ , that is, all nodes in the α subtree are smaller than The values ​​of all nodes are less than the value of node y, and the value of node y is less than all nodes in the θ subtree. In a binary search tree, if the value of node y is greater than the value of node x, then node x is in the left subtree of node y, as shown in Figure (c); or node y is in the left subtree of node x In the right subtree, as shown in Figure (d). Therefore, α < x < β < y < θ can also be expressed by the structure of figure (d). This is rotation, which does not destroy the properties of binary search trees.

Node is red, father is red, grandfather and uncle are black. Specific situation 1

In Figure (a), node is the left child node of father, and father is the left child of grand. Node, node < father < θ < grand < uncle. In this case, father < grand can be expressed as father is the left subtree of grand, or as grand is the right subtree of father. Therefore, father and grand in figure (a) are rotated. Although the rotation will not destroy The properties of a binary search tree, but after rotation, the properties of a red-black tree will be destroyed, so the color of the nodes needs to be adjusted.

Color change

So after the picture (a) is rotated, grand should be changed to red, father should be changed to black, and it should be changed into picture (b) to complete the insertion.

Node is red, father is red, grandfather and uncle are black. Specific situation 2

node is the right child node of father, and father is the right child node of grand, as shown below ( e), is the reversal of specific situation 1.

##That is, uncle < grand < θ < father < node , rotate father and grand in figure (e), and after changing color, it becomes figure (f ) to complete the insertion.

Node is red, father is red, grandfather and uncle are black. Specific situation three

node is the right child node of father, and father is the left child node of grand, as shown below ( m).

After rotating node and father in Figure (m), it becomes Figure (n), and treating father as a new node becomes the specific situation 1. Again After rotating and changing color, the insertion is completed.

Node is red, father is red, grandfather and uncle are black. Specific situation 4

node is the right child node of father, and father is the left child node of grand, as shown below ( i), is the reversal of specific situation three.

After rotating the node and father in figure (i), it becomes figure (j). When father is regarded as the new node, it becomes the specific situation 2. Again After rotating and changing color, the insertion is completed.

Scenario 3.2

node, father and uncle are red, grandfather is black.

As shown in the picture above (k), instead of rotating, the grand is colored red, the father and uncle are colored black, and the grand is used as a new node to judge the situation. If grand is used as a new node, it becomes case 2, and the insertion is completed; if it becomes case 3.1, after adjustment, the insertion is completed; if it is still case 3.2, continue to change the color of grand, father and uncle, and node The node moves up. If the new node node has no parent node, it becomes case 1. The root node is colored black, and the insertion is completed.

To sum up



Case 1Case 2##Case 3.1node, father is red, grand, uncle is black Rotate once or twice and recolorCase 3.2node, Father, uncle are red, grand is blackRecolor father, uncle, grand, grand is the new node

##node situation
Operation
Node is red, no father Recolor node
node is red and father is black


##Code


// 结点
function Node(value) {
 this.value = value
 this.color = &#39;red&#39; // 结点的颜色默认为红色
 this.parent = null
 this.left = null
 this.right = null
}

function RedBlackTree() {
 this.root = null
}

RedBlackTree.prototype.insert = function (node) {
 // 以二叉搜索树的方式插入结点
 // 如果根结点不存在,则结点作为根结点
 // 如果结点的值小于node,且结点的右子结点不存在,跳出循环
 // 如果结点的值大于等于node,且结点的左子结点不存在,跳出循环
 if (!this.root) {
 this.root = node
 } else {
 let current = this.root
 while (current[node.value <= current.value ? &#39;left&#39; : &#39;right&#39;]) {
  current = current[node.value <= current.value ? &#39;left&#39; : &#39;right&#39;]
 }
 current[node.value <= current.value ? &#39;left&#39; : &#39;right&#39;] = node
 node.parent = current
 }
 // 判断情形
 this._fixTree(node)
 return this
}

RedBlackTree.prototype._fixTree = function (node) {
 // 当node.parent不存在时,即为情形1,跳出循环
 // 当node.parent.color === &#39;black&#39;时,即为情形2,跳出循环
 while (node.parent && node.parent.color !== &#39;black&#39;) {
 // 情形3
 let father = node.parent
 let grand = father.parent
 let uncle = grand[grand.left === father ? &#39;right&#39; : &#39;left&#39;]
 if (!uncle || uncle.color === &#39;black&#39;) {
  // 叶结点也是黑色的
  // 情形3.1
  let directionFromFatherToNode = father.left === node ? &#39;left&#39; : &#39;right&#39;
  let directionFromGrandToFather = grand.left === father ? &#39;left&#39; : &#39;right&#39;
  if (directionFromFatherToNode === directionFromGrandToFather) {
  // 具体情形一或二
  // 旋转
  this._rotate(father)
  // 变色
  father.color = &#39;black&#39;
  grand.color = &#39;red&#39;
  } else {
  // 具体情形三或四
  // 旋转
  this._rotate(node)
  this._rotate(node)
  // 变色
  node.color = &#39;black&#39;
  grand.color = &#39;red&#39;
  }
  break // 完成插入,跳出循环
 } else {
  // 情形3.2
  // 变色
  grand.color = &#39;red&#39;
  father.color = &#39;black&#39;
  uncle.color = &#39;black&#39;
  // 将grand设为新的node
  node = grand
 }
 }

 if (!node.parent) {
 // 如果是情形1
 node.color = &#39;black&#39;
 this.root = node
 }
}

RedBlackTree.prototype._rotate = function (node) {
 // 旋转 node 和 node.parent
 let y = node.parent
 if (y.right === node) {
 if (y.parent) {
  y.parent[y.parent.left === y ? &#39;left&#39; : &#39;right&#39;] = node
 }
 node.parent = y.parent
 if (node.left) {
  node.left.parent = y
 }
 y.right = node.left
 node.left = y
 y.parent = node
 } else {
 if (y.parent) {
  y.parent[y.parent.left === y ? &#39;left&#39; : &#39;right&#39;] = node
 }
 node.parent = y.parent
 if (node.right) {
  node.right.parent = y
 }
 y.left = node.right
 node.right = y
 y.parent = node
 }
}

let arr = [11, 2, 14, 1, 7, 15, 5, 8, 4, 16]
let tree = new RedBlackTree()
arr.forEach(i => tree.insert(new Node(i)))
debugger
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future. .

Related articles:

js ajax progress bar code when loading

Two solutions to Ajax cross-domain problems Method

Based on ajax, click to load more without refreshing and load to this page


##

The above is the detailed content of Detailed explanation of red-black tree insertion and examples of Javascript implementation methods. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. Mar 28, 2024 pm 12:50 PM

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

How to enter bios on Colorful motherboard? Teach you two methods How to enter bios on Colorful motherboard? Teach you two methods Mar 13, 2024 pm 06:01 PM

Colorful motherboards enjoy high popularity and market share in the Chinese domestic market, but some users of Colorful motherboards still don’t know how to enter the bios for settings? In response to this situation, the editor has specially brought you two methods to enter the colorful motherboard bios. Come and try it! Method 1: Use the U disk startup shortcut key to directly enter the U disk installation system. The shortcut key for the Colorful motherboard to start the U disk with one click is ESC or F11. First, use Black Shark Installation Master to create a Black Shark U disk boot disk, and then turn on the computer. When you see the startup screen, continuously press the ESC or F11 key on the keyboard to enter a window for sequential selection of startup items. Move the cursor to the place where "USB" is displayed, and then

How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) May 01, 2024 pm 12:01 PM

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

How to set font size on mobile phone (easily adjust font size on mobile phone) How to set font size on mobile phone (easily adjust font size on mobile phone) May 07, 2024 pm 03:34 PM

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

Summary of methods to obtain administrator rights in Win11 Summary of methods to obtain administrator rights in Win11 Mar 09, 2024 am 08:45 AM

A summary of how to obtain Win11 administrator rights. In the Windows 11 operating system, administrator rights are one of the very important permissions that allow users to perform various operations on the system. Sometimes, we may need to obtain administrator rights to complete some operations, such as installing software, modifying system settings, etc. The following summarizes some methods for obtaining Win11 administrator rights, I hope it can help you. 1. Use shortcut keys. In Windows 11 system, you can quickly open the command prompt through shortcut keys.

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) May 04, 2024 pm 06:01 PM

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

Detailed explanation of Oracle version query method Detailed explanation of Oracle version query method Mar 07, 2024 pm 09:21 PM

Detailed explanation of Oracle version query method Oracle is one of the most popular relational database management systems in the world. It provides rich functions and powerful performance and is widely used in enterprises. In the process of database management and development, it is very important to understand the version of the Oracle database. This article will introduce in detail how to query the version information of the Oracle database and give specific code examples. Query the database version of the SQL statement in the Oracle database by executing a simple SQL statement

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

See all articles