题目
分析
简单的搜索题目。只需要从根节点开始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



