Leetcode--Java--559. N 叉树的最大深度

Leetcode--Java--559. N 叉树的最大深度,第1张

Leetcode--Java--559. N 叉树的最大深度 题目描述

给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。

样例描述

思路

BFS 层序遍历 / DFS 递归

  1. 在层序遍历过程中,每次队列d出完所有元素就层数加一。
  2. 加入队列时,扫描完该结点的所有孩子结点。

DFS 递归

  1. 从root所有子节点中取最大深度,并在此基础上加一(加上root结点的深度)
代码

BFS


class Solution {
    public int maxDepth(Node root) {
         int level = 0;
         Deque q = new linkedList<>();
         if (root != null) {
             q.offer(root);
         }
         while (!q.isEmpty()) {
             int size = q.size();
             //层数加一
             level ++;
             for (int i = 0; i < size; i ++ ) {
                Node node = q.poll();
                //只要有孩子就加入队列
                for (Node child: node.children) {
                    if (child != null) {
                        q.offer(child);
                    }
                }
             }
         }
         return level;

    }
}

DFS


class Solution {
    public int maxDepth(Node root) {
        //到空就返回0
        if (root == null) return 0;
        int res = 0;
        //统计所有子节点的最大深度
        for (Node child: root.children) {
            res = Math.max(res, maxDepth(child));
        }
        //返回(加上root后)的深度
        return res + 1;

    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5576019.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存