Detailed explanation of the steps to implement red-black tree in JS
This time I will bring you a detailed explanation of the steps to implement a red-black tree with JS. What are the precautions for implementing a red-black tree with JS. The following is a practical case, let's take a look.
Properties of red-black trees
A binary search tree that satisfies the following properties is a red-black tree
Each node is either black or red.
The root node is black.
Each leaf node (NIL) is black.
If a node is red, both of its child nodes are black.
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 one path is better than the other The path is twice as long 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 a 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
Inserting a node Finally, 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 and the insertion is completed.
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 above picture (c) is part of a binary search tree, where x, y are nodes, α, β, θ are the 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, it can be expressed as father is the left subtree of grand, or it can be expressed 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.
To sum up
node situation | Operation | |
---|---|---|
Case 1 | Node is red, no father | Recolor node |
Case 2 | Node is Red, father is black | |
node, father is red, grand, uncle is black | Rotate once Or twice, and recolor | |
node,father,uncle is red and grand is black | Change father,uncle,grand Recolor, grand as new node |
// 结点 function Node(value) { this.value = value this.color = 'red' // 结点的颜色默认为红色 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 ? 'left' : 'right']) { current = current[node.value <= current.value ? 'left' : 'right'] } current[node.value <= current.value ? 'left' : 'right'] = node node.parent = current } // 判断情形 this._fixTree(node) return this } RedBlackTree.prototype._fixTree = function (node) { // 当node.parent不存在时,即为情形1,跳出循环 // 当node.parent.color === 'black'时,即为情形2,跳出循环 while (node.parent && node.parent.color !== 'black') { // 情形3 let father = node.parent let grand = father.parent let uncle = grand[grand.left === father ? 'right' : 'left'] if (!uncle || uncle.color === 'black') { // 叶结点也是黑色的 // 情形3.1 let directionFromFatherToNode = father.left === node ? 'left' : 'right' let directionFromGrandToFather = grand.left === father ? 'left' : 'right' if (directionFromFatherToNode === directionFromGrandToFather) { // 具体情形一或二 // 旋转 this._rotate(father) // 变色 father.color = 'black' grand.color = 'red' } else { // 具体情形三或四 // 旋转 this._rotate(node) this._rotate(node) // 变色 node.color = 'black' grand.color = 'red' } break // 完成插入,跳出循环 } else { // 情形3.2 // 变色 grand.color = 'red' father.color = 'black' uncle.color = 'black' // 将grand设为新的node node = grand } } if (!node.parent) { // 如果是情形1 node.color = 'black' 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 ? 'left' : 'right'] = 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 ? 'left' : 'right'] = 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))) debuggerI believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to php Chinese website Other related articles!
Recommended reading:
js deduplication and optimization of numerical arraysDetailed explanation of the steps to globally introduce bass.scss into VueThe above is the detailed content of Detailed explanation of the steps to implement red-black tree in JS. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The default map on the iPhone is Maps, Apple's proprietary geolocation provider. Although the map is getting better, it doesn't work well outside the United States. It has nothing to offer compared to Google Maps. In this article, we discuss the feasible steps to use Google Maps to become the default map on your iPhone. How to Make Google Maps the Default Map in iPhone Setting Google Maps as the default map app on your phone is easier than you think. Follow the steps below – Prerequisite steps – You must have Gmail installed on your phone. Step 1 – Open the AppStore. Step 2 – Search for “Gmail”. Step 3 – Click next to Gmail app

WeChat is one of the social media platforms in China that continuously launches new versions to provide a better user experience. Upgrading WeChat to the latest version is very important to keep in touch with family and colleagues, to stay in touch with friends, and to keep abreast of the latest developments. 1. Understand the features and improvements of the latest version. It is very important to understand the features and improvements of the latest version before upgrading WeChat. For performance improvements and bug fixes, you can learn about the various new features brought by the new version by checking the update notes on the WeChat official website or app store. 2. Check the current WeChat version We need to check the WeChat version currently installed on the mobile phone before upgrading WeChat. Click to open the WeChat application "Me" and then select the menu "About" where you can see the current WeChat version number. 3. Open the app

When logging into iTunesStore using AppleID, this error saying "This AppleID has not been used in iTunesStore" may be thrown on the screen. There are no error messages to worry about, you can fix them by following these solution sets. Fix 1 – Change Shipping Address The main reason why this prompt appears in iTunes Store is that you don’t have the correct address in your AppleID profile. Step 1 – First, open iPhone Settings on your iPhone. Step 2 – AppleID should be on top of all other settings. So, open it. Step 3 – Once there, open the “Payment & Shipping” option. Step 4 – Verify your access using Face ID. step

Having issues with the Shazam app on iPhone? Shazam helps you find songs by listening to them. However, if Shazam isn't working properly or doesn't recognize the song, you'll have to troubleshoot it manually. Repairing the Shazam app won't take long. So, without wasting any more time, follow the steps below to resolve issues with Shazam app. Fix 1 – Disable Bold Text Feature Bold text on iPhone may be the reason why Shazam is not working properly. Step 1 – You can only do this from your iPhone settings. So, open it. Step 2 – Next, open the “Display & Brightness” settings there. Step 3 – If you find that “Bold Text” is enabled

Windows 11, as the latest operating system launched by Microsoft, is deeply loved by users. In the process of using Windows 11, sometimes we need to obtain system administrator rights in order to perform some operations that require permissions. Next, we will introduce in detail the steps to obtain system administrator rights in Windows 11. The first step is to click "Start Menu". You can see the Windows icon in the lower left corner. Click the icon to open the "Start Menu". In the second step, find and click "

Screenshot feature not working on your iPhone? Taking a screenshot is very easy as you just need to hold down the Volume Up button and the Power button at the same time to grab your phone screen. However, there are other ways to capture frames on the device. Fix 1 – Using Assistive Touch Take a screenshot using the Assistive Touch feature. Step 1 – Go to your phone settings. Step 2 – Next, tap to open Accessibility settings. Step 3 – Open Touch settings. Step 4 – Next, open the Assistive Touch settings. Step 5 – Turn on Assistive Touch on your phone. Step 6 – Open “Customize Top Menu” to access it. Step 7 – Now you just need to link any of these functions to your screen capture. So click on the first

Is the clock app missing from your phone? The date and time will still appear on your iPhone's status bar. However, without the Clock app, you won’t be able to use world clock, stopwatch, alarm clock, and many other features. Therefore, fixing missing clock app should be at the top of your to-do list. These solutions can help you resolve this issue. Fix 1 – Place the Clock App If you mistakenly removed the Clock app from your home screen, you can put the Clock app back in its place. Step 1 – Unlock your iPhone and start swiping to the left until you reach the App Library page. Step 2 – Next, search for “clock” in the search box. Step 3 – When you see “Clock” below in the search results, press and hold it and

If you don't have control over the zoom level in Safari, getting things done can be tricky. So if Safari looks zoomed out, that might be a problem for you. Here are a few ways you can fix this minor zoom issue in Safari. 1. Cursor magnification: Select "Display" > "Cursor magnification" in the Safari menu bar. This will make the cursor more visible on the screen, making it easier to control. 2. Move the mouse: This may sound simple, but sometimes just moving the mouse to another location on the screen may automatically return it to normal size. 3. Use Keyboard Shortcuts Fix 1 – Reset Zoom Level You can control the zoom level directly from the Safari browser. Step 1 – When you are in Safari
