(Data structure) binary tree hierarchy traversal (java achieve)

Traverse the level:

From top to bottom and then from left to right (breadth tree priority, the need to use the queue)

1. the roots into the queue,

2, loop until the queue is empty

1) Remove the head of the queue node

2) The first team around the child nodes removed (do not get, I do not insert)

 //层次遍历
    public static void levelOrderTraversal(Node root){
        if(root==null){
            return;
        }
        Queue<Node> queue=new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            Node front=queue.remove();
            System.out.println(front.value);
            if(front.left!=null){
               queue.add(front.left);
            }
            if(front.right!=null){
                queue.add(front.right);
            }
        }
    }

Another method is to write a two-dimensional array form, e.g.

 

 

Write a two-dimensional array of layer by layer to print, then you need a binary tree layers (layers starting from 0), if the size and number of layers is equal to a two-dimensional array, it would need in a two-dimensional array to add a one array, advance to the next level. Similar to the method described above and the remaining

  //层次遍历利用二维数组形式写出
    public static class Element{
        int level;
        Node node;
    }
    public static List<List<Character>>levelOrder(Node root){
        List<List<Character>> retList=new ArrayList<>();
        if(root==null){
            return retList;
        }
        Queue<Element> queue=new LinkedList<>();
        Element e=new Element();
        e.node=root;
        e.level=0;
        queue.add(e);
        while(!queue.isEmpty()){
            Element front=queue.remove();
            if(front.level==retList.size()){
                retList.add(new ArrayList<>());
            }
            retList.get(front.level).add(front.node.value);

            if(front.node.left!=null){
                Element l=new Element();
                l.node=front.node.left;
                l.level=front.level+1;
                queue.add(l);
            }
            if(front.node.right!=null){
                Element m=new Element();
                m.node=front.node.right;
                m.level=front.level+1;
                queue.add(m);
            }
        }
        return retList;
    }

 

Published 62 original articles · won praise 9 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_43669007/article/details/100122281