Introduction to tree structure of java data structure

Posted by ashishag67 on Tue, 21 Sep 2021 21:22:38 +0200

1. Tree structure

Is an abstract data type or a data structure that implements this abstract data type, which is used to simulate a data set with tree structure.
It has the following characteristics:

①Each node has zero or more child nodes;
②A node without a parent node is called a root node;
③Each non root node has only one parent node;
④In addition to the root node, each child node can be divided into multiple disjoint subtrees;

Basic logical model of tree structure:

2. Terms related to tree structure

1. Root node: it cannot be said that the root node is the first node in the tree structure. This is a wrong and incomplete statement. I think the correct statement is that there are only child nodes but no nodes. This conclusion is implemented in the tree structure. If it is not understood correctly, it is difficult to find errors when the data of the tree structure is incorrect.
2. Child node: a node with both parent and child nodes.
3. Leaf node: a node that has only a parent node but no child nodes
4. Node degree: refers to the number of subtrees owned by a node, that is, the number of child nodes of the node. A node with both parent and child nodes can be called a subtree.
5. Height of the tree: refers to the current node plus its hierarchical child nodes. for instance

K node is a leaf node at the bottom of the tree. It is generally defined as that the height of K is 1 at the lowest, and so on. The height of O is 1 and the height of P is 1. M node is the parent node of leaf node o, counting from bottom to top. The height of M node is 2. So what is the height of the G node? The height from G-L is 2 and the height from G-M-O node is 3. What is the height of G node? The correct answer is 3

3. Binary tree structure

Binary tree: a tree with at most two subtrees per node is called a binary tree. Under the concept of binary tree, the concepts of full binary tree and complete binary tree are derived
1. Full binary tree: except that the last layer has no child nodes, all nodes on each layer have two child nodes. It can also be understood that all nodes except leaf nodes have two child nodes. When the number of nodes reaches the maximum, all leaf nodes must be on the same layer
2. Complete binary tree: if the depth of the binary tree is h, the number of nodes in all other layers (layers 1 to (h-1)) except layer h reaches the maximum, and all nodes in layer h are continuously concentrated on the leftmost, which is a complete binary tree.

4. Code implementation of simple binary tree

1, Simple structure

public class Tree {
    private Node root; //Root node in tree structure
    //Three constants are defined for three traversal modes of tree structure
    private static final int PREVIOUS_ORDER = 1; 
    private static final int MEDIUM_ORDER = 2;
    private static final int END_ORDER = 3;

//Use internal classes to complete the definition of node classes
    private class Node{
        private Student data;
        private Node left;
        private Node right;

        public Node(Student data, Node left, Node right){
            this.data = data;
            this.left = left;
            this.right = right;
        }
    }

//Define an add method for the root node. For nodes that are not root nodes, the add method of addElement will be used
    public void addNode(Student data){
        if(root == null){
            root = new Node(data,null,null);
            return;
        }
        addElement(data,root);
    }

2, Adding method of child node

    //Follow the principle of small left and large right of binary tree
    private void addElement(Student node, Node root){
        if(root.left != null && node.getId() < root.data.getId()){//The ID of the entered node is greater than the ID of the root node of the tree, so traverse to the left
            addElement(node,root.left);
            return;
        }else if(root.right != null && node.getId() > root.data.getId()){//Traverse right
            addElement(node,root.right);
            return; //It is necessary to return after traversal, otherwise the middle node will be replaced in the recursive backtracking process
        }
		//Traverse to the last element of the tree node, and then judge whether the input node ID is greater than the last node ID
        if(root.left == null && node.getId() < root.data.getId()){
            root.left = new Node(node,null,null);
        }else{
            root.right = new Node(node,null,null);
        }
    }

3, Tree traversal

 //Traverse the tree structure according to the customer's input
    public void showElementByOrder(int order){
        order(root,order);
    }
    //Three traversal methods of tree structure: pre order traversal, middle order traversal and post order traversal
    private void order(Node root,int order){
    	//Preorder traversal
        if(order == PREVIOUS_ORDER) System.out.println(root.data.getName());
        if(root.left != null){
            order(root.left,order);
        }
		//Medium order traversal
        if(order == MEDIUM_ORDER) System.out.println(root.data.getName());

        if(root.right != null){
            order(root.right,order);
        }
		//Post order traversal
        if(order == END_ORDER) System.out.println(root.data.getName());
    }

4, Modular writing method for tree traversal

    //Traverse the tree structure according to the customer's input
    public void showElementByOrder(int order){
        switch(order){
            case PREVIOUS_ORDER:preOder(root);break;
            case MEDIUM_ORDER:mediumOrder(root);break;
            case END_ORDER:endOrder(root);break;
        }
        order(root,order);
    }

	//Preorder traversal
    private void preOder(Node root){
        System.out.println(root.data.getName());
        if(root.left != null){
            preOder(root.left);
        }
        if(root.right != null){
            preOder(root.right);
        }
    }

	//Medium order traversal
    private void mediumOrder(Node root){
        if(root.left != null){
            mediumOrder(root.left);
        }
        System.out.println(root.data.getName());
        if(root.right != null){
            mediumOrder(root.right);
        }
    }

	//Postorder traversal
    private void endOrder(Node root){
        if(root.left != null){
            endOrder(root.left);
        }
        if(root.right != null){
            endOrder(root.right);
        }
        System.out.println(root.data.getName());
    }

5. Finds the specified element

For the element search in the tree structure, I modified the preOrder method and used this method to search nodes

//In essence, the search method is to traverse the whole tree to find the specified node
private Node preOder(Node root , int id){
   	if(root.data.getId() == id){
         return root; //Returns when the node is found
    	}
    	//When the input ID is less than the ID of the current node, it will traverse to the left
    	//(adding a judgment condition can not traverse the whole tree, which can greatly reduce the execution times and save more time)
    if(root.left != null && root.data.getId() > id){
            return preOder(root.left,id);
        }
        //When the input ID is greater than the ID of the current node, it traverses to the right
    if(root.right != null && root.data.getId() < id) {
         return preOder(root.right,id);
      }
      //If the specified node is not found in the whole tree, NULL is returned
      return null;
  }

//Enter the ID of the person to be searched by the user
  public Student searchElement(int id){
      Node temp = preOder(root,id);
      return temp == null ? null : temp.data;
  }

6. Testing

1, Add elements and traverse the tree

public class Text {

    public static void main(String[] args) {
       Tree tree = new Tree();
       tree.addNode(new Student(111,"Zhang San",25));
       tree.addNode(new Student(222,"Li Si",55));
       tree.addNode(new Student(55,"Wang Wu",31));
       tree.addNode(new Student(555,"Zhao Liu",55));
       tree.showElementByOrder(1);
       tree.showElementByOrder(2);
       tree.showElementByOrder(3);
    }
}

Tree structure logical model after adding successfully

result
Traverse the tree.showElementByOrder(1) using the preamble;
Zhang San
Wang Wu
Li Si
Zhao Liu
Traverse the tree.showElementByOrder(2) using the middle order;
Wang Wu
Zhang San
Li Si
Zhao Liu
Traverse tree.showElementByOrder(3) using post order;
Wang Wu
Zhao Liu
Li Si
Zhang San

2, Finds the specified element in the tree structure

  Student temp = tree.searchElement(55);
  System.out.println(temp.getName());

result
Wang Wu

7. Summary

1. In the data structure, we mainly understand two models: logical model and memory model, followed by the knowledge used. For example, this paper uses a lot of recursion, so recursion has to pay attention to two logical ideas: recursion and backtracking. The recurrence is good, mainly in the backtracking process. If you are not careful, you will find an error that is difficult to find. This error will not lead to an error in program operation, but will lead to data error,
2. As developers, they are not afraid of program error reporting. They are afraid of data errors during the operation of the program. As the saying goes: data is money. The data error caused by the program is nothing more than letting the money slip away under your eyes.
Don't ask me why or how to pay attention to the backtracking process? Then I can only say, "you write less code". Your attention can save you a lot of "money". As for how to pay attention to the backtracking process, in fact, many in the program world need experience.
3. Remember, in the procedural world, don't talk about theory, because if you haven't tried, theory may be just theory.

Topics: Java Algorithm data structure Binary tree