给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
例如,给定一个
我们应返回其最大深度,3。
说明:
树的深度不会超过 1000。
树的节点总不会超过 5000。
递归(深搜)
class Solution {
public:
int maxDepth(Node* root) {
if(!root)
return 0;
int n=root->children.size();
int max_node=0;
for(int i=0;i<n;++i)
{
int m=maxDepth(root->children[i]);
max_node=max(max_node,m); // 找到子节点最多节点那条
}
return max_node+1;
}
};
层序遍历(BFS)
/*
// 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) {
if(!root)
return 0;
queue<Node*> qu;
qu.push(root);
int max_node=0;
while(!qu.empty())
{
max_node++;
int n=qu.size(); // 当前层的节点数
while(n--)
{
Node* node=qu.front();
qu.pop();
int l=node->children.size();
for(int i=0;i<l;++i)
{
qu.push(node->children[i]);
}
}
}
return max_node;
}
};