题目
该题目是简单的一道递归题目,针对任意一个子树,分别遍历其根节点的所有孩子节点的每个深度,取出最大的那个深度即可。
代码如下:
import common.NxNode;
public class P559MaximumDepthOfNAryTree {
public static void main(String[] args) {
Solution solution = new P559MaximumDepthOfNAryTree().new Solution();
System.out.println("Hello world");
}
//leetcode submit region begin(Prohibit modification and deletion)
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public int maxDepth(NxNode root) {
return maxDepthDg(root);
}
public int maxDepthDg(NxNode root) {
if (root == null) {
return 0;
}
int curNodeMaxDepth = 1;
for (NxNode nd : root.children) {
curNodeMaxDepth = Math.max(1 + maxDepthDg(nd), curNodeMaxDepth);
}
return curNodeMaxDepth;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}