Simple handwritten red-black tree

Based red-black tree "algorithm," a book of insertion and deletion. Read different materials, but also have different implementations, but the end result is much the same, I feel this is easier to understand, on the use of this simple approach to achieve. Entity type definition tree node # `` `java private static final boolean RED = true; private static final boolean BLACK = false; / ** * * red-black tree node structure stored value, the left node, right node and a color ( true red, false black) * default add a red node * * @param */ static final class RedBlackTreeNode > { E val; RedBlackTreeNode left; RedBlackTreeNode right; boolean color = RED; RedBlackTreeNode (E val) {this.val = val;}} `` `defined herein simply a bit red-black tree, and only node, this is not the map structure kv. If the structure is defined kv when compared to Comparative k. Use of generics, and to support the comparison (inherited from Comparable), or can not compare the size of the insert. Then define a value, left and right node node, then the default color is red. Add a constructor to # define common methods are mainly to do is insert and delete nodes, in order to see whether the added convenience of a printing method in order traversal of `` `java public class RedBlackTree > { RedBlackTreeNode head; public void add (E e) {...} public void remove (E e) {...} public void printTree () {...}} `` `These common definitions to methods for external calls, particularly implementation can put private methods. # Conversion operation in the conversion of red-black tree has three primary: L, D, discoloration. Next we come to realize these three methods. Two important properties ** rotating operation can maintain red-black tree: the perfect balance of order and ## L ** `` `java private RedBlackTreeNode rotateLeft(RedBlackTreeNode node) {// change position RedBlackTreeNode result = node.right; node.right = result.left; result.left = node; // color change result.color = node.color; node.color = RED; return result;} `` `** When the right node empty black or red, left nodes, the need for left-handed operation. ** first define a variable storage node and right, then left and right node of the node as a parent node (incoming parameters) to the right node. In this case the right node (defined variables) associated disconnected. Is then defined variables (right node) node as the left argument node (on the right has been assigned to the node before the node parameters left node). Step needed for color change, color definitions of the variables set the color of the parent node (the one does not affect the operation), then the parent node is set to red. The defined variable is returned as the parent node. ## right-handed `` `java private RedBlackTreeNode rotateRight(RedBlackTreeNode node) {// change position RedBlackTreeNode result = node.left; node.left = result.right; result.right = node; // color result.color = node.color; node.color = RED; return result;} `` `** When the node is left left red node, the node has left is red, the need for right-handed operation. ** This is similar to the basic left, the left node as a parent node is returned, then the other nodes have to make sure is not lost, as well as color change does not affect the operation of red-black tree properties. ## color change `` `java private void flipColor (RedBlackTreeNode node) {node.left.color = BLACK; node.right.color = BLACK; node.color = RED;} `` `** When two child nodes are red, a color change is required so that the two child nodes ** turns black, the parent node turns red # complete the implementation of the common methods we have just mentioned above, it is necessary to determine the color of a node, although we define `color` attribute type node, but taking into account other circumstances or write a method for determining a complete color function: ## isRed (Node) `` `java private boolean isRed (RedBlackTreeNode node) {if (node ​​== null) {return false;} return node.color;} `` `black shall return false when the node is empty, or whether the color attribute determination node is red. There is a method in order to print ## printTree () `` `java public void printTree () {print (head);} private void print (RedBlackTreeNode node) {if (node ​​== null) {return;} print (node.left); System.out.print (node.val + ""); print (node.right);} `` `on the outside the method calls the internal method, passing the head node. Because it is in order traversal, so you need to traverse the left node, and then print your own, then traverse the right node. This is a recursive operation, it is necessary to define the termination condition: when the node is empty return. # Embodied # add () `` `java public void add (E val) throws IllegalAccessException {if (val == null) {throw new IllegalAccessException (" not add null value ");} head = addVal (val, head) ; // set the root node to the final black head.color = bLACK;} private RedBlackTreeNode addVal(E val, RedBlackTreeNode node) {// reach the final node, if red is empty a new node if (node ​​== null) {return new RedBlackTreeNode } `` In a common approach first carried out a parameter check, if it is empty you can not compare it to throw an exception. The method then calls the private add nodes: the value of the parameter passed to be added, the head node of the tree. In the private methods first determine whether the incoming node is empty, if empty, create a new red node returns. When the size is determined not empty, is determined by adding the left or right subtree subtree, then a recursive call this method, incoming values ​​and the left or right node of the node to be added, if the node is equal to the current period is returned directly (do not map to re-change value). And after the addition may be adjusted, so it is necessary to re-assignment. The next step is determining whether the predetermined red-black tree, then L, D, discoloration and other operations. At this time it will be readjusted, so it is necessary to re-assignment. After the completion of the operation returns to the public process. Public method in the first color to black node, ensure the characteristic red-black tree. ## remove () `` `java public void remove (E val) throws IllegalAccessException {if (val == null) {throw new IllegalAccessException (" not null-value operation ");} if (head == null) {throw new IllegalAccessException ( "empty trees");} head = removeVal (val, head);} private RedBlackTreeNode removeVal(E val, RedBlackTreeNode } `` `Parameter checking in public methods, if the deletion is null, an exception is thrown. Then when the tree is empty delete operation can not be performed. Delete operations may also be structural changes, so it needs to be re-assigned. Compared to the current node parameter, if small recursively incoming left node, then recursively if large incoming right node, you delete a node in the tree is no longer, I am here it is to throw an exception when the node is empty, you may some not appropriate. If the current node are the same, delete the current node. Then they exposed a problem, when the current node has children if removed. In fact, this is also the case that is divided into several lines 20-26 in the code above: 1. The current node no child nodes, delete the current node that is set to null. 2. The minimum right child node instead of the current node, then delete the minimum node. `` `Java / ** * Get the right side of the lowest node tree * * @param node * @return * / private RedBlackTreeNode getRightMinNode (RedBlackTreeNode node) { RedBlackTreeNode parent = node.right; if (parent.left == null) { node.right = parent.right; return parent; } RedBlackTreeNode result = parent.left; // where there may be optimized while (result.left = null!) {parent = parent.left; result = parent.left;} parent.left = null; return result;} `` `3 when the right node is empty, find the maximum value of the left node as an alternative to the current node, then delete the maximum node. `` `Java private RedBlackTreeNode getLeftMaxNode(RedBlackTreeNode node) { RedBlackTreeNode parent = node.left; if (parent.right == null) { node.right = parent.left; return parent; } RedBlackTreeNode result = parent.right; while (! result.right = null) {parent = parent.right; result = parent.right;} parent.right = null; return result;} `` `After replacement, it is necessary to check whether the characteristic red-black tree need for L, D, discoloration and other operations. Verify # `` `java public static void main (String [] args) throws IllegalAccessException {RedBlackTree redBlackTree = new RedBlackTree (); RedBlackTree.add (1); redBlackTree.add (3); redBlackTree.add (5); redBlackTree.add (7); redBlackTree.add (9); redBlackTree.add (2); redBlackTree.add (4 ); redBlackTree.printTree (); System.out.println (); redBlackTree.remove (2); redBlackTree.printTree (); System.out.println (); redBlackTree.remove (11);} `` `first we followed by adding [1,3,5,7,9,2,4]. The tree is then printed, print out the result as expected result should be the order of 1 to 9. Then we remove the node 2, the insertion process if we will find if you remove drawn 2, will result in two red nodes connected 1,3, which does not comply with the red-black tree, it needs to be adjusted. Then print again to see if the result is wrong. Finally, we delete the value that does not exist, to see if it will complain. `` `Java 1 2 3 4 5 7 9 1 3 4 5 7 9 Exception in thread" main "java.lang.IllegalAccessException: val not exist at RedBlackTree.removeVal (RedBlackTree.java:33) at RedBlackTree.removeVal (RedBlackTree! .java: 38) at RedBlackTree.removeVal (RedBlackTree.java:38) at RedBlackTree.removeVal (RedBlackTree.java:38) at RedBlackTree.remove (RedBlackTree.java:28) at Test. main (Test.java:21) `` `we can see the results meet our requirements through output, then the method can also be viewed by the situation after the debug node 2 deleted node discovery and started painting in the draft version of the agreement. Just insert gives a picture of the process. ! [] (Https://raw.githubusercontent.com/liunaijie/images/master/20191213183308.png) situation after deleting the node 2! [] (Https://raw.githubusercontent.com/liunaijie/images/master/ 20191224112717.png)> This article from the blog article multiple platforms [OpenWrite] (https://openwrite.cn?from=article_bottom) released! Bloggers E-mail: [email protected], there are problems you can mail exchange.

Guess you like

Origin www.cnblogs.com/lnj96/p/12134085.html