[Java] Basics - sort of binary tree

Hello everybody, recently updated a little slow a lot, participated in a number of outside companies and technical training, but also partners with some small talk some technical articles in general is far from ideal, speaking on the content of the tall, stepped on the floor of the process Hang very serious, and the effect is almost not heard, feeling the past few years, the circle is too impetuous, and new technology in droves, anxious to come out yesterday, today it is used on the project. It is worthy of my reflection.

Technology is changing the age is changing, but the only constant is our core technologies: Linux, C, TCP \ IP these, no matter how changes in the superstructure, are encapsulated in just the underlying basis.

I suggest that you have a choice to look for learning resources, not when the leek, to learn the source of knowledge, people do not taste digested knowledge.

In the previous article, we introduced the Collection papers and a HashMap, we are going to introduce the rest of the Map implementation, and today we start to introduce sorted binary tree and red-black tree, for the next TreeMap and TreeSet preparation and by taking It re-Wen Yibo data structure. Ado, we begin the text.

Sorting binary tree

basic concepts

Binary search tree (English: Binary Search Tree), also known as binary search tree , ordered binary tree (ordered binary tree) or sorted binary tree (sorted binary tree), refers to an empty tree or binary tree with the following properties:

  1. If the left subtree of any node is not empty, then the value of the left sub-tree, all the nodes are less than the value of the root node;

  2. If the right subtree of any node is not empty, the right subtree are greater than values ​​of all the nodes of the root node and its value;

  3. Any node of the left and right subtrees are also binary search tree;

  4. There is no equivalent key node. - <Excerpt from Wikipedia> img2018.cnblogs.com/blog/102305... )

As shown in FIG, 2 are sorted binary trees.

Operational rule

The following is a tree structure:

class Node {

        /**
         * 节点
         */
        Object data;
        /**
         * 父节点
         */
        Node parent;
        /**
         * 左子节点
         */
        Node left;
        /**
         * 右子节点
         */
        Node right;
    
    	public Node(Object data, Node parent, Node left, Node right) {
            this.data = data;
            this.parent = parent;
            this.left = left;
            this.right = right;
        }
}
复制代码

Seek

There is a good sort of binary tree search algorithm, when looking for an element, more efficient, and of course standard orientation under the array can not be compared, it is hardware support.

  • First, determine whether the tree is empty, if it is empty then the lookup fails
  • And compare it with the node, if the same is found Return
  • If less than the root node, then recursively the left subtree
  • If greater than with the node, then recursively right subtree
private Node getNode(Object e) {
            Node parent = root;
            while (parent != null) {
                //比较父节点元素 和传入的元素
                int compareValue = e.compareTo(parent.data);
                if(compareValue < 0){
                    //查找左子树
                    parent = parent.left;
                }
                else if(compareValue > 0){
                    //查找右子树
                    parent = parent.right;
                }
                else{
                    return parent;
                }
            }
            return null;
        }
复制代码

insert

To insert an ordered binary tree of nodes in the data elements as follows:

  • If the Tree is empty, then data is inserted as the root node
  • If the data value of the node with equal Returns
  • If the data is less than the value of the node with the insert in the left subtree if the subtree is left empty, the current node is the left child of the root node
  • If the data is greater than with the value of the node, then the insertion into the right subtree, if the right subtree is empty, the current node is a node with a right subtree
private void insertNode(Object o) {
            if (root == null) {
                root = new Node(o, null,null,null);
            }

            Node current = root;
            Node parent = current;
            int compareValue = 0;
            while (current != null) {
                compareValue = o.compareTo(parent.data);
                // 新节点的值 > parent的值
                if(compareValue > 0){
                    //查找右子树
                    current = current.right;
                }else if(compareValue < 0){
                    //查找左子树
                    current = current.left;
                } else {
                    return;
                }
            }
            //创建新节点
            Node newNode = new Node(o, parent, null, null);
            //新节点的值大于 父节点值
            if(compareValue > 0){
                //设置为右子节点
                parent.right = newNode;
            }else{
                //设置为左子节点
                parent.left = newNode;
            }
        }
复制代码

delete

Sort delete binary tree is slightly more complicated:

  • If you want to delete a node is a leaf node
    • You can delete the leaf node
		Node parent = node.parent;
            //要删除的当前节点没有子节点
            if (node.left == null && node.right == null) {
                if (o.compareTo(parent.data)) {
                    parent.right = null;
                } else {
                    parent.left = null;
                }
            }
复制代码

For example, we delete 0001

  • Only one child node node
    • To delete a node for the child node, just like we have a similar list of deleted directly associated with the child node of the parent node
//要删除的元素只有一个子节点
//只有一个左节点
if (node.left != null && node.right == null) {
    //被删除的节点是父节点的左节点
    if (node == parent.left) {
        //父节点的左子节点就是当前节点的左子节点
        parent.left = node.left;
    }
    node.left.parent = parent;
}
复制代码

// 只有一个右节点
else if (node.left == null && node.right != null) {
    if (node == parent.right) {
        parent.right = node.right;
    }
    node.right.parent = node.right;
}
复制代码

  • Node has two children nodes

    • Looking to the successor node to be deleted node, the contents of the current nodes with the content of the next node, delete successor node.

    • No successor node left child, then put the child node to replace the two leaf nodes or a node with only one child.

      //要删除的元素有 2 个子节点
      if (node.left != null && node.right != null) {
          Node leftMaxNode = node.left;
          //查找后继节点(注意,这里的后继节点不是左子节点或者右子节点,而是最大节点)
          while(leftMaxNode.right != null){
              leftMaxNode = leftMaxNode.right;
          }
          //找到的后继节点与当前待删除的节点进行替换
          leftMaxNode.parent = node.parent;
          //把原来的后继节点删除
          leftMaxNode.parent.right = null;
          if(node == node.parent.left){
              node.parent.left = leftMaxNode;
          }
          else{
              node.parent.right = leftMaxNode;
          }
          leftMaxNode.left = node.left;
          leftMaxNode.right = node.right;
          node.parent = node.left = node.right = null;
      
      }
      复制代码

Above all we are talking about highly balanced binary tree sort:

Balance definitions: height difference of the left and right subtrees of any node is at most a.

But there are also extreme, degenerate binary tree directly into the list. such as:

Even without degradation to the list, sorted binary tree if the case of highly unbalanced, the efficiency will be lower.

And balanced binary tree has been sorted we become AVL tree, according to its author GMAdelson-Velsky, EMLandis named. AVL algorithm when inserting and removing nodes, based on one or multiple rotations to re-balance the tree. Of course, we did not write in this case is important to maintain a balance algorithms, just give us first recall. After'll get back to you on articles in specialized data structure.

Red-black tree

Our next talk TreeMap red-black tree is used. Red-black tree (Red-black tree) is similar to the AVL tree is a self-balancing binary search tree, insert and delete nodes by selecting actions to balance, but it is not a highly balanced, but broadly balanced. such as

Red-black tree has the following properties:

  • Node is red or black.
  • The root is black.
  • All leaves are black (leaf node is NIL).
  • Each red node must have two black child nodes. (Red can not have two consecutive nodes on all paths from the root to each leaf.)
  • From any node to all simple paths each leaf contains the same number of black nodes.

Ensure that any red-black tree from a leaf node to follow a path, not a length longer than any other path than twice.

For example, the shortest path 3 -> 2 1 is

The longest path 3 -> 9 -> 15--> 16 is 4. Just 2 times.

Dyeing & rotation

We just say here that at the core of the red-black tree - rotation operation

As also shown

At this time, we insert 20

1559185401041

  • First insert the maximum right subtree, and stained
    • 20 is red is because if set to black, it will lead to a road on the root to leaf path, one more additional black node, this is a very difficult adjustment. But after the set red node, may lead to a conflict of two consecutive red nodes appear, and then the tree can be adjusted by rotating the color swap (color flips)
    • Then the parent node 16 and node 20 of 11 uncle are red, then we can put them dyed black, and re-staining red grandparent node 15

  • At this time, the parent node 11 and 16 of the 15 red and grandparent node 9 is red, then we can jump by a left-handed

We mentioned above the rotation tree. We mention below under Related concepts

  • Left rotation

example:

  • Right rotation

example:


Guess you like

Origin juejin.im/post/5d8c7d57f265da5b8305db60