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


    二叉树按层遍历

    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;
        }
    }
  • 相关阅读:
    selennium模块
    urllib模块
    有关爬虫模块
    爬虫_requests_html
    爬虫x_path
    项目上线
    navicat使用 pymysql操作数据库 sql注入及增删改查
    基本查询语句和方法,连表,子查询
    表与表之间的关系
    存储引擎 数据类型
  • 原文地址:https://www.cnblogs.com/moris5013/p/11811063.html
Copyright © 2020-2023  润新知