1. 程式人生 > >559. Maximum Depth of N-ary Tree - LeetCode

559. Maximum Depth of N-ary Tree - LeetCode

ava scrip esc rip dep etc src ldr problem

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

559. Maximum Depth of N-ary Tree - LeetCode