559. Maximum Depth of N-ary Tree
其实两份代码思路差不多的,都是DFS。但是第二份代码更棒(第一份我写的,第二份我看discuss的)。
用递归的角度:当有一个树的时候,maxDepth(x)求出这棵树的各个儿子的深度。再返回各个儿子的深度的最大值,加上父亲的一层,就是这颗树的深度.
for(auto x:root->children)
depth.push_back(maxDepth(x));
return *max_element(depth.begin(),depth.end())+1;
基准情况:树是空的,或者树没有儿子。
if(root ==NULL)
return 0;
if(root->children.size() == 0)
return 1;
用DFS角度:探索每个分支,到尽头后,再回溯。
code1
class Solution {
public:
int maxDepth(Node* root) {
if(root ==NULL)
return 0;
if(root->children.size() == 0)
return 1;
vector<int> depth;
for(auto x:root->children)
depth.push_back(maxDepth(x));
return *max_element(depth.begin(),depth.end())+1;
}
};
code2
class Solution {
public:
int maxDepth(Node* root) {
if(root ==NULL)
return 0;
int maxdep = 0;
for(auto x:root->children)
maxdep = max(maxdep,maxDepth(x));
return maxdep+1;
}
};