此题是二叉树最大深度的小升级版,递归和迭代都可以用二叉树稍微修改。
递归需要注意,n叉树中的子树是children,不知道有多少子树,所以需
要在判断子树不为空以后遍历root.children,对每个子树递归。
/*
// 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;
int depth = 0;
if (root.children != null) {
for (Node children:root.children) {
//这我先写的depth = Math.max(depth,maxDepth(children))+1,最后return depth
//这是对递归的条件不清楚,depth记录的是当前节点之后的最大深度,所以不需要加上
//该节点之前的深度。
depth = Math.max(depth,maxDepth(children));
}
}
return depth+1;
}
}
迭代:
class Solution {
public int maxDepth(Node root) {
/**
* 迭代法,使用层序遍历
*/
if (root == null) return 0;
int depth = 0;
Queue<Node> que = new LinkedList<>();
que.offer(root);
while (!que.isEmpty())
{
depth ++;
int len = que.size();
while (len > 0)
{
Node node = que.poll();
for (int i = 0; i < node.children.size(); i++)
if (node.children.get(i) != null)
que.offer(node.children.get(i));
len--;
}
}
return depth;
}
}