559. N 叉树的最大深度【简单】

在这里插入图片描述
https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/

/*
// 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 ans=0;
    int maxDepth(Node* root) 
    {
    
    
        if(!root) return 0;
        dfs(root,0);
        return ans+1;
    }
    void dfs(Node *root,int deep)
    {
    
    
        ans=max(ans,deep);
        for(int i=0;i<root->children.size();i++)
        {
    
    
            dfs(root->children[i],deep+1);
        }
    }
};

猜你喜欢

转载自blog.csdn.net/bettle_king/article/details/121462284