leetcode刷题-559. Maximum Depth of N-ary Tree

本文探讨了在LeetCode上关于N-ary树的最大深度问题,提供了两种算法解决方案:深度优先搜索(DFS)的迭代方法和广度优先搜索(BFS)的队列实现。通过这两种方法,可以有效地计算出N-ary树的最深深度。

题目: https://leetcode.com/problems/maximum-depth-of-n-ary-tree/description/

n-ary-tree的数据结果表示

// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};

  DFS算法:迭代

int maxDepth(Node* root) {
        if (root == NULL) return 0;
        int max = 0, n = root->children.size();
        for (int i = 0; i<n; i++)
        {
            int temp=maxDepth(root->children[i]);
            if (temp>max)
                max = temp;
            //max=std::max(max,maxDepth(root->children[i]));
        }
        return max + 1;
    }

BFS算法:队列

int maxDepth(Node* root) {
        if (root == NULL) return 0;
        int res=0;
        queue<Node*> Q;
        Q.push(root);
        while(!Q.empty())
        {
            res++;
            int n=Q.size();
            for(int i=0;i<n;i++)
            {
                Node* t=Q.front();
                
                for(int j=0;j<t->children.size();j++)
                    Q.push(t->children[j]);
                Q.pop();
            }
        }
        return res;
    }

 

转载于:https://www.cnblogs.com/xiaoxue126/p/9487488.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值