2023年6月7日星期三

Understanding Red-Black Tree, With Examples

 Understanding Red-Black Tree, With Examples

A red–black tree is a self-balancing binary search tree. Each node of the binary tree is either red or black. These trees satisfy the following properties:

  1. Every node is either red or black.
  2. The root is black.
  3. Every leaf node (NULL) is black.
  4. If a node is red, both its children are black.
  5. Every simple path from a node to a descendant leaf contains the same number of black nodes.

These properties ensure that the tree is roughly balanced - height of the tree is O(log n) where n is the number of nodes.
Example:Trova il miglior laptop per te in base al budget e al caso di utilizzo in base ai nostri test approfonditi.

10(B)
/ \
5(R) 15(B)
/ \
2(B) 8(R)

Here 10 is the root node which is black. Nodes 5 and 15 are children of 10. 5 is red and 15 is black.
Nodes 2 and 8 are children of 5. 2 is black and 8 is red.

Operations on red-black trees involve rotations to maintain the balance properties:

  • Insertion - When a new node is inserted, it is colored red. Rotations may be needed to fix violations.

  • Deletion - When a node is deleted, its child may cause a violation. Recoloring and rotations fix this.

  • Search - Searching a key in the tree just follows the left/right pointers like in a regular BST.

  • Balancing factors:

    • Height balancing - Max difference between heights of children is 1
    • Size balancing - Size difference between subtrees is atmost 2

Hope this helps! Let me know if you have any other questions.

没有评论:

发表评论

注意:只有此博客的成员才能发布评论。

Also Read: