Shocked! There are people who don’t understand binary trees! 99% of programmers can do it. Just click in!

Time:2021-1-25

What! You’re in! It seems that you are the one percent programmer. Since I don’t know what a binary tree is, I’ll tell you.

Shocked! There are people who don't understand binary trees! 99% of programmers can do it. Just click in!

1. Trees

The so-called binary tree is essentially a tree. If you want to know what a binary tree is, you need to know what a tree looks like. what! How can I not understand what a tree looks like? It’s just a pole! Then you’re stupid like a pole.

Shocked! There are people who don't understand binary trees! 99% of programmers can do it. Just click in!

The wonderful shape of the object above is the tree! (I think this is a tree)

Did you find the characteristics of trees? Trees are composed of trunks and branches. There are many branches distributed around one trunk. This is the natural tree. Since binary tree is also a tree, it can’t get rid of the structure of natural tree.

Tree in computer is a kind of abstract data type (ADT), which is used to simulate data set with tree structure. It is a set of n (n > 0) finite nodes with hierarchical relationship by connecting their edges. It’s called “tree” because it looks like an upside down tree, that is, it has roots up and leaves down.

Do you understand? Dull, generally speaking, the tree in the computer is the tree in nature. Upside down, Lu Zhishen pulled the willow upside down. You know, he created the tree in the computer (funny)

What do you still don’t understand? Are you more stupid than stupidity! If you don’t understand, I’ll draw you a pictureShocked! There are people who don't understand binary trees! 99% of programmers can do it. Just click in!

This picture is vivid.

But it’s just the shape of a tree in nature. What does a computer tree look like?

Shocked! There are people who don't understand binary trees! 99% of programmers can do it. Just click in!

(please don’t make complaints about painting).

① Node: the circles in the figure above, such as a, B, C, all represent nodes. Nodes generally represent some entities. In java object-oriented programming, nodes generally represent objects.

② Edge: the line connecting a node is called an edge, and the edge represents the association relationship of the node. Generally, the only way to get from one node to another is to follow a path with edges. In Java, it usually means reference.

There are many kinds of trees. A tree with more than two children in the upper node is called multi tree, and each node can only have two children at most. This is also the focus of our explanation.

2. Common terms of tree

  Shocked! There are people who don't understand binary trees! 99% of programmers can do it. Just click in!

  ①、route: following the edge of a node from one node to another, the order of nodes is called “path”.

Take chestnut for example: the path from a to h passes through four nodes a, B, D and H. This is called a path

  ②、rootThe node at the top of the tree is called the root. A tree has only one root.

  ③、Parent node: if a node has children, it is called the parent of its children; B is the parent of D.

  

To put it simply, one branch has two branches, so this branch is the father of those two branches.

  ④、Child node: the root node of the subtree contained in a node is called the child node of the node; D is the child node of B.

  ⑤、Brother node: nodes with the same parent node are called brothers to each other; for example, D and E in the figure above are called brothers to each other.

  ⑥、Leaf node: nodes without children are called leaf nodes, or leaf nodes. For example, h, e, F and G in the figure above are leaf nodes.

  

That is to say, if a branch has no branches, it will grow leaves. The branch with leaves is the leaf branch, that is, the leaf node

  ⑦、subtree: each node can be used as the root of the subtree, and it and all its children, and the children of the children are included in the subtree.

  

Have you ever heard of willow? You can take root and grow into a tree by pulling out a branch and inserting it into the soil. A subtree is a branch of a willow tree.

  ⑧、Hierarchy of nodes: defined from the root, the root is the first layer, the child node of the root is the second layer, and so on.

  ⑨、depthFor any node n, the depth of n is the length of the unique path from root to N, and the depth of root is 0;

  

The height of any branch of a tree to the ground

  ⑩、height: for any node n, the height of n is the longest path from n to a leaf, and the height of all leaves is 0;

3. The structure of binary tree

A binary tree is also a tree. Nature and the structure of a tree are similar. By name, a binary tree is a tree with two branches. So a binary tree is a tree in which a node can only have two children. Now we should all know what a binary tree is, and how does a binary tree work? How efficient is it to find a node, insert a new node, delete a node and traverse the tree? Let’s introduce it one by one.

Since it is a binary tree, it must be divided into the left branch and the right branch. Then I will write two branches for him.

private String rightNode;//The branch on the right
private String leftNode;//The branch on the left

Then the branch has, and we have to write out the method of searching and inserting for the tree

public Tree {
/*
    //Find node
    public String find(Object key);
    //Insert new node
    public boolean insert(Object key);

4. Binary tree sorting

The so-called sorting is that a value is arranged in a certain order. What is the method of binary tree sorting?

There are seven numbers here: 3, 5, 2, 6, 4, 1, 7. Then, according to our normal order from large to small, that is 1, 2, 3, 4, 5, 6, 7. But in our binary tree, there must be a root node, so we take the first number of the array as the root, so the root is 3. The number smaller than the root is placed on the left side of the root, and the number larger than the root is placed on the right side of the root. So let’s continue to sort down. The second number is 5, which is larger than 3, and it is placed on the right side of the root. Next, if 2 is smaller than 3, it is placed on the left side of 3, and so on. The final results are as follows:

Shocked! There are people who don't understand binary trees! 99% of programmers can do it. Just click in!

At this time, let’s consolidate the knowledge points we just mentioned. The root of the binary tree is 3, and the parent node has 3, 2, 5 and 6. Leaf nodes, that’s 1, 4, 7.

Now let’s see how to implement this process in Java code.

import java.util.List;
import java.util.ArrayList;

public class NodeDemo {
    public static void main(String args[]){
        //Define a bunch of numbers
        int[] numbers = {6,5,8,2,6,6,9};
        //Declare and instantiate the node object
        Node roots = new Node();
        //Use foreach to add each value of numbers to the node of binary tree with add method
        for(int number : numbers){
            roots.add(number);        //Call add method
        }
        //Output the value of each node in the binary tree
        System.out.println(roots.values());
    }
}

class Node {
    private Node leftNode;                //Define a left node
    private Node rightNode;                //Define a right node
    private Object value;                //Define the current value of the node

    //Define the add method of binary tree, and add it as mentioned above. The formal parameter value is the value passed from the numbers array
    public void add(Object value){
        //Judge whether the current node has a value, if not, assign the value passed by numbers to the current node
        if(this.value == null){
            this.value = value;
        }else{    
            //If the value passed is less than or equal to the value of the current node, a node object is instantiated to the left node of the modified node, and the left node calls the add method
            if((Integer)value <= (Integer)this.value){
                if(this.leftNode == null){
                    this.leftNode = new Node();
                }
                this.leftNode.add(value);
            }else{
                //If the value passed is greater than the value of the current node, a node object is instantiated to the right node of the modified node, and the right node calls the add method
                if(this.rightNode == null){
                    this.rightNode = new Node();
                }
                this.rightNode.add(value);
            }
        }
    }

4. Find the node matching value

  1. First, give a value a, and a will compare the size with the root.
  2. The node larger than the root is larger than the child node on the right.
  3. Smaller than the root than the child node on the left
  4. If the matching value is found, return true, if not, return flas

    Let’s look at the code
//Find node
//Compare the main method above
public boolean find(int key) {
    private int findnumber = 10;
    while(key != null){
        if(findnumber > key){//The current value is larger than the search value, search the left subtree
            findnumber = key.leftNode;
        }else if(findnumber < key){//The current value is smaller than the search value, search the right subtree
            findnumber = key.rightNode;
        }else{
            return findnumber;
        }
    }
    return null;//Traversing the entire tree, no find, return null
}

5. Traversing binary tree

Traversal tree is based on a specific order to access each node of the tree. More commonly used are preorder traversal, middle order traversal and postorder traversal. The most commonly used binary search tree is the middle order traversal.

① Middle order traversal: left subtree root node right subtree

② Preorder traversal: root node left subtree right subtree

3. Post order traversal: left subtree right subtree root node

  Shocked! There are people who don't understand binary trees! 99% of programmers can do it. Just click in!

//Middle order traversal
public void infixOrder(Node current){
    if(current != null){
        infixOrder(current.leftChild);
        System.out.print(current.data+" ");
        infixOrder(current.rightChild);
    }
}

//Preorder traversal
public void preOrder(Node current){
    if(current != null){
        System.out.print(current.data+" ");
        preOrder(current.leftChild);
        preOrder(current.rightChild);
    }
}

//Postorder traversal
public void postOrder(Node current){
    if(current != null){
        postOrder(current.leftChild);
        postOrder(current.rightChild);
        System.out.print(current.data+" ");
    }
}

6. Why use binary tree

For a general binary search tree, the expected height (i.e. when it is a balanced tree) is log2n, and the time complexity (O (log2n)) of each operation is also determined by it. However, in some extreme cases (such as when the inserted sequence is ordered), the binary search tree will degenerate into an approximate chain or chain, and the time complexity of its operation will degenerate into a linear one, that is, O (n). We can avoid this situation by randomizing the establishment of binary search tree, but after many operations, we always choose to replace the successor of the node to be deleted when deleting, which will reduce the number of nodes on the right, so that the tree tends to sink to the left. At the same time, it will destroy the balance of the tree and increase the time complexity of its operation.

The query speed is related to the height of the binary tree. The higher the height is, the slower the query is, which is inversely proportional. When the binary tree is an ordered node, it will degenerate into a linked list structure. To query a data, it is necessary to traverse the linked list, so the efficiency is greatly reduced, and there will be a balanced binary tree.

This work adoptsCC agreementReprint must indicate the author and the link of this article