LeetCode 559. N叉树的最大深度(C++)

这篇博客探讨了如何解决LeetCode中的559题,即找到N叉树的最大深度。通过层序遍历而非递归的方法,避免了超时问题。文中给出了一个执行时间为52ms的C++解决方案,该方案在提交中超过了72.48%的用户。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。

例如,给定一个 3叉树 :

 

 

我们应返回其最大深度,3。

说明:

  1. 树的深度不会超过 1000
  2. 树的节点总不会超过 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;
}();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值