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 children;

    Node() {}

    Node(int _val, vector _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*/
        
    }
};

你可能感兴趣的:(LeetCode:559. Maximum Depth of N-ary Tree)