0559. Maximum Depth of N Ary Tree

0559. Maximum Depth of N-ary Tree #

题目 #

给定一个 n 叉树,找到其最大深度。

最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。

思路 #

  • 层序遍历

代码 #

class Node {
    public int val;
    public List<Node> children;
    
    public Node() {}
    public Node(int _val) { val = _val; }
    public Node(int _val, List<Node> _children) { val = _val; children = _children; }
}
class Solution {
    public int maxDepth(Node root) {
        if (root == null) return 0;
        
        int depth = 0;
        
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);
        
        while (queue.size() != 0) {
            int layerSize = queue.size();
            depth += 1;
            for (int i = 0; i < layerSize; i++) {
                for (Node child: queue.poll().children) {
                    queue.offer(child);
                }
            }
        }
        
        return depth;
    }
}