广度优先搜索--二叉树按层遍历

二叉树按层遍历

public class WideFirstSearch {

    public static void main(String[] args) {
        
        Node root = new Node("A");
        root.left = new Node("B");
        root.right = new Node("C");
        root.left.left = new Node("D");
        root.left.right = new Node("E");
        root.left.right.left = new Node("G");
        root.right.right = new Node("F");
        List<List<String>> res =  wfs(root);
        for(int i = 0 ; i<res.size() ; i++) {
            System.out.print(""+(i+1)+"层: ");
            res.get(i).forEach(x -> System.out.print(x + " "));
            System.out.println();
        }
    }
    
    public static List<List<String>> wfs(Node root){
        List<List<String>> res = new ArrayList<List<String>>();
        LinkedList<Node> queue = new LinkedList<Node>();
        queue.addLast(root);
        while(!queue.isEmpty()) {
            int size = queue.size();
            List<String> list = new ArrayList<>();
            while(size>0) {
                Node temp = queue.pollFirst();
                list.add(temp.value);
                if(temp.left != null) {
                    queue.addLast(temp.left );
                }
                if(temp.right != null) {
                    queue.addLast(temp.right);
                }
                size --;
            }
            res.add(list);
        }
        return res;
    }
}

class Node{
    String value;
    Node left;
    Node right;
    Node(String value){
        this.value = value;
    }
}
原文地址:https://www.cnblogs.com/moris5013/p/11811063.html