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

LeetCode-Maximum Depth of N-ary Tree

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