编号559:N叉树的最大深度

编号559:N叉树的最大深度

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

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

例如,给定一个 3叉树 :

图片

我们应返回其最大深度,3。

思路

跟二叉树的层序遍历相似,当遍历到每一层时,其深度加一

代码

 public static int getDepth3(Node root){
        Queue<Node> queue = new ArrayDeque<>();
        int depth = 0;
        queue.add(root);
        while(!queue.isEmpty()){
            depth++;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                Node temp = queue.poll();
                for (int j = 0; j <temp.children.size ; j++) {
                    queue.add(temp.children);
                }
            }
        }
        return depth;
    }

posted @ 2021-04-05 20:53  胡木杨  阅读(50)  评论(0)    收藏  举报