Traversal of java tree

Posted by rinjani on Mon, 17 Jan 2022 00:03:03 +0100

In programming life, we always meet tree structure. These days, we just need to operate the tree structure, so we can record our own operation mode and process. Now suppose there is such a tree, (it doesn't matter whether it is a binary tree or not, and the principle is the same)

1. Breadth first traversal

The English abbreviation is BFS, that is, bread first search. In terms of process inspection, the nodes of each layer are accessed in turn, and after accessing one layer, they enter the next layer, and each node can only be accessed once. For the above example, the results of breadth first traversal are: A, B, C, D, e, F, G, h, I (assuming that each layer node accesses from left to right).

First insert the left node and then the right node into the queue, so that leaving the queue is to first insert the left node and then the right node.

Breadth first traversal of the tree requires * * Queue * * to store node objects. The Queue is characterized by first in first out. For example, the access to the above tree is as follows:

First, insert node A into the queue with element (A);

Pop up node A, and insert the left and right nodes of node A into the queue in turn. B is at the head of the queue, C is at the end of the queue, (B, c). At this time, node A is obtained;

Continue to pop up the team head element, that is, pop up B, and insert the left and right nodes of B into the queue. C is at the head of the team and E is at the end of the team (C,D, e). At this time, node B is obtained;

Continue to pop up, that is, pop up C, and insert the left, middle and right nodes of node C into the queue in turn (D,E,F,G,H). At this time, node C is obtained;

Pop up D. at this time, D has no child nodes, and the elements in the queue are (E,F,G,H), so node D is obtained;

. . . and so on..

Code: take the binary tree as an example to traverse the values of all nodes

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/

public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        ArrayList<Integer> lists=new ArrayList<Integer>();
        if(root==null)
            return lists;
        Queue<TreeNode> queue=new LinkedList<TreeNode>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode tree=queue.poll();
            if(tree.left!=null)
                queue.offer(tree.left);
            if(tree.right!=null)
                queue.offer(tree.right);
            lists.add(tree.val);
        }
        return lists;
    }
}

2. Depth first traversal

The English abbreviation is DFS, namely Depth First Search In brief, the process is to go deep into every possible branch path, and each node can only access it once. For the above example, the result of depth first traversal is: A,B,D,E,I,C,F,G,H. (suppose to go to the left of the child node first).

Depth first traversal of each node requires the use of a stack data structure. Stack is characterized by first in and last out. The whole traversal process is as follows:

First press the right node into the stack, then the left node, so that the left node is first and then the right node out of the stack.
First, press node A into the stack, stack (A);

Pop up node A, and press the child nodes C and B of A into the stack. At this time, B is at the top of the stack, stack(B,C);

Pop up node B, and press the child nodes E and D of B into the stack. At this time, D is at the top of the stack, stack (D,E,C);

Pop up node D and no child nodes are pressed in. At this time, e is at the top of the stack, stack (E, C);

Pop up node E and press the child node i of e into stack (I,C);

... go down one by one, and finally the traversal is completed.

Code: also take binary tree as an example. non-recursive

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/

public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        ArrayList<Integer> lists=new ArrayList<Integer>();
        if(root==null)
            return lists;
        Stack<TreeNode> stack=new Stack<TreeNode>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode tree=stack.pop();      //First press the right node into the stack, then the left node, so that the left node is first and then the right node out of the stack.
            if(tree.right!=null)
                stack.push(tree.right);
            if(tree.left!=null)
                stack.push(tree.left);
            lists.add(tree.val);
        }
        return lists;
    }
}

Depth first recursive implementation:

public void depthOrderTraversalWithRecursive()  
    {  
        depthTraversal(root);  
    }  
      
    private void depthTraversal(TreeNode tn)  
    {  
        if (tn!=null)   
        {  
            System.out.print(tn.value+"  ");  
            depthTraversal(tn.left);  
            depthTraversal(tn.right);  
        }         
    }

Quoted articles:
Link: Java traversal tree (depth first + breadth first).

Topics: Java data structure linked list