最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
例如,给定一个 3叉树
:
我们应返回其最大深度,3。
说明:
- 树的深度不会超过
1000
。 - 树的节点总不会超过
5000
。
基本思路:层序遍历,不要用递归,会超时。
我的解答(执行用时: 52 ms, 在Maximum Depth of N-ary Tree的C++提交中击败了72.48%的用户):
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
int maxDepth(Node* root) {
if(root==NULL)return 0;
int depth=0;
vector<Node*> path;
path.push_back(root);
while(!path.empty())
{
int count=path.size();
depth++;
while(count>0)
{
Node* node=path.front();
for(int i=0;i<node->children.size();i++)
{
path.push_back(node->children[i]);
}
path.erase(path.begin());
count--;
}
}
return depth;
}
};
执行用时为36ms的范例:
class Solution {
public:
int maxdep;
void dfs(Node* root,int dep){
if(root->children.size()==0){
maxdep=max(maxdep,dep);
return;
}
for(auto i:root->children){
dfs(i,dep+1);
}
}
int maxDepth(Node* root){
maxdep=0;
if(root==NULL){
return 0;
}
else if(root->children.size()==0){
return 1;
}else{
dfs(root,1);
return maxdep;
}
}
};
static const auto io_speed_up = [](){
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
return 0;
}();