当前位置:首页 » 《随便一记》 » 正文

leetcode每日一题-559:N叉树的最大深度_苦泉的博客

5 人参与  2022年05月24日 11:43  分类 : 《随便一记》  评论

点击全文阅读


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

链接

N 叉树的最大深度


题目

在这里插入图片描述



分析

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



代码

C++

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

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<Node> 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

点击全文阅读


本文链接:http://zhangshiyu.com/post/40673.html

深度  题目  作者  
<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1