559. Maximum Depth of N-ary Tree - LeetCode

Question

559. Maximum Depth of N-ary Tree

Solution

题目大意: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 depth = 0;
        for (Node child : root.children) {
            depth = Math.max(depth, maxDepth(child));
        }
        return depth + 1;
    }
}

猜你喜欢

转载自www.cnblogs.com/okokabcd/p/9567359.html
今日推荐