題目:N叉樹的最大深度
給定一個 N 叉樹,找到其最大深度。
最大深度是指從根節點到最遠葉子節點的最長路徑上的節點總數。
複製程式碼
示例:
例如,給定一個 3叉樹 :
複製程式碼

我們應返回其最大深度,3。
複製程式碼
思考:
採用遞迴,N叉樹的最大深度等於它的最大子樹深度+1,遞迴遍歷其所有子樹,取深度最大的結果+1即為結果。
複製程式碼
實現:
class Solution {
public int maxDepth(Node root) {
if(root == null) return 0;
int dep = 0;
for(Node node : root.children){
int d = maxDepth(node);
dep = Math.max(dep, d);
}
return dep+1;
}
}複製程式碼