給定一個 N 叉樹,找到其最大深度。
最大深度是指從根節點到最遠葉子節點的最長路徑上的節點總數。
例如,給定一個 3叉樹 :
我們應返回其最大深度,3。
說明:
樹的深度不會超過 1000。
樹的節點總不會超過 5000。
DFS
/*
// 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;//條件1
int max = 0;
for(Node cur:root.children){
int depth = maxDepth(cur);
max = Math.max(max,depth);
}
return max+1;//遞歸結束條件2
}
}
BFS
/*
// 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 max = 0;
Queue<Node> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
max++;
while(size>0){
size--;
Node cur = queue.poll();
for(Node curr:cur.children){
queue.offer(curr);
}
}
}
return max;
}
}