编辑代码


import java.util.*;

public class Main {
    public static class Node {
        int id;
        ArrayList<Node> children = new ArrayList<>();
        int level = 0;

        public Node(int id) {
            this.id = id;
        }

        @Override
        public String toString() {
            return String.format("id:%s,level:%s", this.id, this.level);
        }
    }

    public static void main(String[] args) {
        Node a = new Node(1);
        Node b = new Node(2);
        Node c = new Node(3);
        Node d = new Node(4);
        Node e = new Node(5);
        Node f = new Node(6);
        a.children.add(b);
        a.children.add(c);
        b.children.add(d);
        b.children.add(e);
        b.children.add(f);
        measureLevel(a);
    }

    public static void measureLevel(Node node) {
        //TODO write your impl here
        Queue<Node> queue = new LinkedList<>();
        int level = 0;
        int size = 1;
        int curSize = 0;
        queue.offer(node);
        while(!queue.isEmpty()) {
            Node n = queue.poll();
            n.level = level;
            System.out.println(n.toString());
            List<Node> childrens = n.children;
            for(Node child : childrens) {
                queue.offer(child);
            }
            if(++curSize == size) {
                level ++;
                size = queue.size();
                curSize = 0;
            }
        }
    }
}