前言
深度优先,递归上!
题目
源码
/*
// 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) {
// 方法1,递归
if(root==null){
return 0;
}else if(root.children.isEmpty()){
return 1;
}
List<Integer> h =new LinkedList<>();
int max=0;
for (Node tmp:root.children){
h.add(maxDepth(tmp));
}
return Collections.max(h)+1;
// 方法2,迭代
// Queue<Pair<Node,Integer>> q=new LinkedList<>();
// if(root!=null){
// q.add(new Pair(root,1));
// }
// int depth=0;
// while(!q.isEmpty()){
// Pair<Node,Integer> cur = q.poll();
// root=cur.getKey();
// int cur_val=cur.getValue();
// if(root!=null){
// depth=Math.max(cur_val,depth);
// for(Node tmp:root.children){
// q.add(new Pair(tmp,depth+1));
// }
// }
// }
// return depth;
}
}