题目
给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
例如,给定一个 3叉树 :
我们应返回其最大深度,3。
说明:
树的深度不会超过 1000。
树的节点总不会超过 5000。
思路+代码
思路其实和算二叉树深度是差不多的,递归到最深,返回深度,用一个变量记录深度,在返回时进行比较
class Solution {
public int depth(Node root, int deep) {
if(root==null){
return deep;
}
int de = deep;
for(int i=0;i<root.children.size();i++){
int res = depth(root.children.get(i), de+1);
if(res>deep){ //记录最大深度
deep = res;
}
}
return deep;
}
public int maxDepth(Node root) {
if(root == null){
return 0;
}else{
return depth(root, 1);
}
}
}
运行结果:
题解中的非递归代码:
//迭代:层序遍历
public int maxDepth2(Node root) {
if(root == null) return 0;
Queue<Node> queue = new LinkedList<>();
queue.add(root);
int maxDepth = 0;
while(!queue.isEmpty()){
int count = queue.size();
maxDepth++;
while(count > 0){
count--;
Node cur = queue.poll();
for(Node node : cur.children){
if(node != null)
queue.add(node);
}
}
}
return maxDepth;
}
作者:mmmmmJCY
链接:https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/solution/java-di-gui-he-die-dai-by-zxy0917/
来源:力扣(LeetCode)
还是递归吧(