本题使用层序遍历则和二叉树的最大深度没有太大区别,只有在节点入队时,二叉树是左右子节点入队,而N叉树则是子节点列表入队。
/*
// 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) {
queue<Node*> que;
int depth = 0;
if(root != nullptr){
que.push(root);
}
while(!que.empty()){
depth++;
int size = que.size();
for(int i = 0; i < size; i ++){
Node* cur = que.front();
que.pop();
if(cur != nullptr){
for(int j = 0; j < cur->children.size(); j++){
if(cur->children[j] != nullptr){
que.push(cur->children[j]);
}
}
}
}
}
return depth;
}
};
使用递归则需要去记录子节点深度的最大值,并进行返回
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;
}
};