给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
例如,给定一个 3叉树 :
我们应返回其最大深度,3。
说明:
- 树的深度不会超过 1000。
- 树的节点总不会超过 5000。
解法一
bfs,使用队列
/*
// 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(Node root) {
//特判
if (root == null) return 0;
//bfs
//队列
Queue<Node> queue = new LinkedList<>();
queue.add(root);
int depth = 0;
while (!queue.isEmpty()) {
//每次循环深度加1
depth++;
//每次循环遍历上一层保存的所有节点
int size = queue.size();
for (int i = 0; i < size; i++) {
//把节点的所有子节点放到队列中
Node node = queue.poll();
queue.addAll(node.children);
}
}
return depth;
}
}
可能是因为队列的增删操作,执行时间差了些。
解法二
dfs,使用递归
class Solution {
public int maxDepth(Node root) {
//dfs
//递归
return dfs(root, 1);
}
//递归
private int dfs(Node node, int depth) {
//出口
if (node == null) return depth - 1;
//递归当前节点的所有子节点
//max为当前节点的最大深度
int max = depth;
for (int i = 0; i < node.children.size(); i++) {
//保存子节点返回的最大深度
int d = dfs(node.children.get(i), depth + 1);
if (d > max) {
max = d;
}
}
return max;
}
}