leetcode每日一题-559: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
|