题目地址:
https://leetcode.com/problems/maximum-depth-of-n-ary-tree/
求多叉树的高度。用分治法。
import java.util.List;
public class Solution {
public int maxDepth(Node root) {
if (root == null) {
return 0;
}
int max = 0;
if (root.children != null) {
for (Node child : root.children) {
max = Math.max(max, maxDepth(child));
}
}
return max + 1;
}
}
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;
}
}
时间复杂度 ,空间复杂度 , 为树的高度,也是递归栈深度。