559. N 叉树的最大深度
题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/submissions/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目描述
题目分析
- 递归
class Solution {
public:
int maxDepth(Node* root) {
if(root == nullptr) return 0;
int depth = 0;
for(int i = 0; i < root->children.size(); i++){
depth = max(depth, maxDepth(root->children[i]));
}
return depth + 1;
}
};
- 迭代
class Solution {
public:
int maxDepth(Node* root) {
if(root == nullptr) return 0;
queue<Node*> que;
que.push(root);
int depth = 0;
while(!que.empty()){
depth++;
int n = que.size();
while(n--){
Node* temp = que.front();
que.pop();
for(int i = 0; i < temp->children.size(); i++){
que.push(temp->children[i]);
}
}
}
return depth;
}
};