递归求最大深度,DFS和BFS均可
这里采用DFS
题意ref{:target=”_blank”}
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 maxDepth(Node* root) {
return dfs(root);
}
int dfs(Node* root) {
if(!root)return 0;
int res = 0;
for(auto ch : root->children) {
res = max(res, dfs(ch));
}
return res+1;
}
};