​LeetCode刷题实战559:N 叉树的最大深度

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 N叉树的最大深度,我们先来看题面:

https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/

Given a n-ary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).

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

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

N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。

示例                         

cb989bdba56274b1d7a6fd103dc17354.png

解题

遍历每一颗子树即可

class Solution {
    public int maxDepth(Node root) {
        if(root == null) return 0;
        int max = 1;
        int dep = 0;
        Iterator<Node> iterator = root.children.iterator();
        while(iterator.hasNext()){
            dep = maxDepth(iterator.next())+1;
            max = max > dep ? max : dep;
            dep = 0;
        }
        return max;
    }
}

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-540题汇总,希望对你有点帮助!

LeetCode刷题实战541:反转字符串 II

LeetCode刷题实战542:01 矩阵

LeetCode刷题实战543:二叉树的直径

LeetCode刷题实战544:输出比赛匹配对

LeetCode刷题实战545:二叉树的边界

LeetCode刷题实战546:移除盒子

LeetCode刷题实战547:省份数量

LeetCode刷题实战548:将数组分割成和相等的子数组

LeetCode刷题实战549:二叉树中最长的连续序列

LeetCode刷题实战550:游戏玩法分析 IV

LeetCode刷题实战551:学生出勤记录 I

LeetCode刷题实战552:学生出勤记录 II

LeetCode刷题实战553:最优除法

LeetCode刷题实战554:砖墙

LeetCode刷题实战555:分割连接字符串

LeetCode刷题实战556:下一个更大元素 III

LeetCode刷题实战557:反转字符串中的单词 III

LeetCode刷题实战558:四叉树交集

947d5cfbd66b536005f7ae5a188a10b9.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值