


Detailed explanation of red-black tree insertion and examples of Javascript implementation methods
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
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 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 α
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
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.
##node situation | Operation | |
---|---|---|
Node is red, no father | Recolor node | |
node is red and father is black | ||
Rotate once or twice and recolor | Case 3.2 | |
Recolor father, uncle, grand, grand is the 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))) debugger
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 loadingTwo 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!

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1
Powerful PHP integrated development environment
