给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
说明:
- 树的深度不会超过 1000。
- 树的节点总不会超过 5000。
class Solution {
public:
int maxDepth(Node* root) {
if(root == NULL)
return 0;
int cnt = 0;
queue<Node*> q;
q.push(root);
while(!q.empty())
{
int s = q.size();
cnt++;
while(s--)
{
Node* node = q.front();
q.pop();
for(int i = 0; i < node ->children.size(); i++)
{
if(node ->children[i] != NULL)
{
q.push(node ->children[i]);
}
}
}
}
return cnt;
}
};
本文介绍了一种求解N叉树最大深度的算法,通过使用队列进行层次遍历,计算从根节点到最远叶子节点的最长路径上的节点总数。此方法适用于树的深度不超过1000,节点总数不超过5000的情况。
361

被折叠的 条评论
为什么被折叠?



