zoukankan      html  css  js  c++  java
  • 广度优先搜索--二叉树按层遍历

    二叉树按层遍历

    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;
        }
    }
  • 相关阅读:
    Java静态方法中使用注入类
    Java FTP辅助类
    Java SFTP辅助类
    MyBatis学习总结——批量查询
    MyBatis学习总结—实现关联表查询
    Redis集群搭建与简单使用
    SQL管理工具
    MySQL锁机制
    MySQL权限管理
    yii框架下使用redis
  • 原文地址:https://www.cnblogs.com/moris5013/p/11811063.html
Copyright © 2011-2022 走看看