給定一個 N 叉樹,找到其最大深度。
最大深度是指從根節點到最遠葉子節點的最長路徑上的節點總數。
例如,給定一個 3叉樹 :
?
我們應返回其最大深度,3。
說明:
?? ?樹的深度不會超過 1000。
?? ?樹的節點總不會超過 5000。
思路見代碼
/*
// 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 LinkedList<>();for (Node item : root.children) {heights.add(maxDepth(item)); }return Collections.max(heights) + 1;}}
}
?