LeetCode-Maximum Depth of N-ary Tree

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/82926092

Description:
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.

For example, given a 3-ary tree:

在这里插入图片描述

We should return its max depth, which is 3.

Note:

  • The depth of the tree is at most 1000.
  • The total number of nodes is at most 5000.

题意:返回一颗N叉树的最大深度,即根节点到最远叶子节点的距离;

解法:我们可以利用递归来计算N叉树的最大深度;对于每一个节点,我们遍历其所有节点,那么这个节点的深度就是其子节点中的最大深度加1;对于子节点,递归调用求解子节点的深度;

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

    public Node() {}

    public Node(int _val,List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    public int maxDepth(Node root) {
        if (root == null) {
            return 0;
        }
        int max = 1;
        for (int i = 0; i < root.children.size(); i++) {
            max = Math.max(max, maxDepth(root.children.get(i)) + 1);
        }
        return max;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/82926092
今日推荐