题目描述:
标签:树 深度优先搜索 广度优先搜索
给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。
代码:
思路分析:思路同二叉树的最大深度。不过添加子结点进入队列使用的是增强for循环。
《方法一:广度优先搜索(其实也就是层序遍历)》
/*
// 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;
}
Queue<Node> queue = new LinkedList<Node>();
int level = 0;
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
for(int i = 1; i <= size;i++){
Node node = queue.poll();
List<Node> nodes = node.children;
for(Node childNode : nodes){
queue.offer(childNode);
}
}
level++;
}
return level;
}
}
《方法二:深度优先搜索(其实也就是递归)》
注意:链表求最大值的方法有Collections.max()
/*
// 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;
}else if(root.children.isEmpty()){
return 1;
}else{
List<Integer> heights = new ArrayList<Integer>();
for(Node node : root.children){
heights.add(maxDepth(node));
}
return Collections.max(heights) + 1;
}
}
}