leetcode-559-Maximum-Depth-of-N-ary-Tree

描述


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:

img

We should return its max depth, which is 3.

Note:

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

分析


深度优先遍历一颗 N 叉树。

解决方案1(Java)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/*
// 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;
}
if (root.children.size() == 0) {
return 1;
}
int result = 0;
for (int i = 0; i < root.children.size(); i++) {
result = Math.max(result, maxDepth(root.children.get(i)));
}
return result + 1;
}
}

相关问题


(E) Maximum Depth of Binary Tree

题目来源