Maximum Depth of N-ary Tree
题目描述:
给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
例如,给定一个 3叉树 :
解题思路:本题和之前的二叉树最大深度一样,只不过就是孩子结点的数目不一样,采用两种递归方法,一种是自顶向下,一种是自顶向上(这个要想一下,比较好),详细过程参见之前的二叉树一题。
/*
class Solution {
public:
int max_dep=0;
int maxDepth(Node* root) {
if(!root)return 0;
get_max_dep(root,1);
return max_dep;
}
void get_max_dep(Node* root,int cur_dep){
if(!root)return;
if(cur_dep>max_dep)max_dep=cur_dep;
for(int i=0;i<root->children.size();i++){
get_max_dep(root->children[i],cur_dep+1);
}
}
};
*/
class Solution {
public:
int maxDepth(Node* root) {
if(!root)return 0;
int max_value=0;
for(int i=0;i<root->children.size();i++){
max_value=max(maxDepth(root->children[i]),max_value);
}
return max_value+1;
}
};