Problem:
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.
For example, given a 3-ary tree:
Explanation:
求n叉树的最大深度。
My Thinking:
- 遍历结点的孩子,维持一个孩子结点中最大的深度,返回该深度+1即可。
- 使用迭代进行层序遍历
My Solution:
(1)
class Solution {
public int maxDepth(Node root) {
if(root==null)
return 0;
int childrenmaxdepth=0;
for(Node node:root.children){
int nowchildrenmax=maxDepth(node);
childrenmaxdepth=Math.max(childrenmaxdepth,nowchildrenmax);
}
return 1+childrenmaxdepth;
}
}
(2)
class Solution {
public int maxDepth(Node root) {
Queue<Node> queue=new LinkedList<>();
if(root!=null)
queue.add(root);
int maxdepth=0;
while(!queue.isEmpty()){
int size=queue.size();//取出i,遍历i次,相当于层序
for(int i=0;i<size;i++){
Node n=queue.poll();
for(Node node:n.children)
queue.add(node);
}
maxdepth++;
}
return maxdepth;
}
}
Optimum Thinking:
Optimum Solution: