栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

leetcode每日一题-559:N叉树的最大深度

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leetcode每日一题-559:N叉树的最大深度

leetcode每日一题-559:N叉树的最大深度 链接 N 叉树的最大深度
题目



分析

简单的搜索题目。只需要从根节点开始dfs一下整个N叉树就可以得到答案了。主要是对dfs要理解和掌握N叉树的遍历。



代码

C++


class Solution {
public:

    int res = 0;

    int maxDepth(Node* root) {
        if(root == nullptr) return res;
        dfs(root, 1);
        return res;
    }

    void dfs(Node* root, int deep)
    {
        res = max(res, deep);

        for(auto ve : root->children)
        {
            dfs(ve, deep + 1);
        }
    }
};

Java

class Solution {
    public int maxDepth(Node root) {
        if (root == null) {
            return 0;
        }
        int maxChildDepth = 0;
        List children = root.children;
        for (Node child : children) {
            int childDepth = maxDepth(child);
            maxChildDepth = Math.max(maxChildDepth, childDepth);
        }
        return maxChildDepth + 1;
    }
}

作者:LeetCode-Solution

Javascript

var maxDepth = function(root) {
    if (!root) {
        return 0;
    }
    let maxChildDepth = 0;
    const children = root.children;
    for (const child of children) {
        const childDepth = maxDepth(child);
        maxChildDepth = Math.max(maxChildDepth, childDepth);
    }
    return maxChildDepth + 1;
};

作者:LeetCode-Solution
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/581700.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号