1. 程式人生 > >559. N叉樹的最大深度(Java 和 python)

559. N叉樹的最大深度(Java 和 python)

給定一個N叉樹,找到其最大深度。

最大深度是指從根節點到最遠葉子節點的最長路徑上的節點總數。

例如,給定一個 3叉樹 :

我們應返回其最大深度,3。

說明:

  1. 樹的深度不會超過 1000
  2. 樹的節點總不會超過 5000

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;
        } else {
            int max = 0;
            for (int i = 0; i < root.children.size(); i++) {  // 遍歷子結點,找出子結點中的最大深度
                max = Math.max(max, maxDepth(root.children.get(i)));
            }
            return 1+max;
        }
    }
}

python:

"""
# Definition for a Node.
class Node(object):
    def __init__(self, val, children):
        self.val = val
        self.children = children
"""
class Solution(object):
    def maxDepth(self, root):
        """
        :type root: Node
        :rtype: int
        """
        if not root:
            return 0
        if not root.children:
            return 1
        return 1 + max(self.maxDepth(child) for child in root.children)