LeetCode:559. Maximum Depth of N-ary Tree

题目要求

Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
给定一个n-树,求其最大深度。


举例.PNG

题目分析

本题要求的一棵树的最大深度,其实就是求一颗树的深度,也可以理解成求根节点的深度,关于树的深度请参考:

所以可以将这个问题分冶。即将求一个节点的深度转换成求其子节点的最大深度+1,这个思想可以用递归的方法来实现。

本题解析

/*
// 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 )
            return 0;

        int depth = 0;
        
        for( auto &child: root->children )
        {    /*遍历子节点*/
            depth = max( depth, maxDepth(child));      /*求出子节点的最大深度*/
        }
        
        return depth + 1;    /*返回子节点的最大深度 + 1*/
        
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容