一、题目描述
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.
Nary-Tree input serialization is represented in their level order traversal,
each group of children is separated by the null value (See examples).
Input: root = [1,null,3,2,4,null,5,6]
Output: 3
二、题解
方法一:递归
class Solution {
public int maxDepth(Node root) {
return dfs(root);
}
private int dfs(Node root) {
if (root == null)
return 0;
int max = 0;
for (Node child : root.children) {
max = Math.max(dfs(child), max);
}
return max + 1;
}
}
stack 迭代
在这里,因为栈 FILO 的特性,我们不能取出先入栈的结点,所以我们也就不能从上到下依次将节点入队。所以我们需要用一个 curDepth 记录每一层结点的高度。
public int maxDepth(Node root) {
if (root == null)
return 0;
int maxDepth = 0;
int curDepth = 1;
Stack<Pair> stack = new Stack<>();
stack.push(new Pair(root, curDepth));
while (!stack.isEmpty()) {
Pair pair = stack.pop();
curDepth = pair.depth;
Node node = pair.node;
maxDepth = Math.max(maxDepth, curDepth);
for (Node child : pair.node.children) {
stack.push(new Pair(child, curDepth + 1));
}
}
return maxDepth;
}
class Pair {
Node node;
int depth;
public Pair(Node _node, int _depth) {
node = _node;
depth = _depth;
}
}
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,
方法二:
* 错误版本,一层的大小不是 node.children,size()
,而是 queue.size()
,
public int maxDepth(Node root) {
int maxDepth = 0;
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
Node node = queue.poll();
int level_size = queue.size();
while (level_size-- > 0) {
for (Node n : node.children) {
queue.add(n);
}
}
maxDepth++;
}
return maxDepth;
}
* 正确版本,每次只取出一层,每次将取出的一层的所有结点的孩子 children 入队。
public int maxDepth(Node root) {
if (root == null)
return 0;
int maxDepth = 0;
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int level_size = queue.size();
while (level_size-- > 0) {
Node node = queue.poll();
for (Node n : node.children) {
queue.add(n);
}
}
maxDepth++;
}
return maxDepth;
}
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,