StreamingAssets載入資源(音訊、圖片)原始碼
阿新 • • 發佈:2020-12-08
Leetcode 559 N叉樹的最大深度
資料結構定義:
給定一個 N 叉樹,找到其最大深度。 最大深度是指從根節點到最遠葉子節點的最長路徑上的節點總數。 N 叉樹輸入按層序遍歷序列化表示,每組子節點由空值分隔(請參見示例)。 示例 1: 1 / | \ 3 2 4 / \ 5 6 輸入:root = [1,null,3,2,4,null,5,6] 輸出:3 /* 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[] depthes = new int[root.children.size()]; for(int i = 0;i< root.children.size(); ++i){ depthes[i] = maxDepth(root.children.get(i)); } return depthes.length > 0 ? Arrays.stream(depthes).max().getAsInt() + 1 : 1; } }
遞迴的簡潔方式:
class Solution {
public int maxDepth(Node root) {
if(root == null){
return 0;
}
int depth = 1;
for(Node children :root.children){
depth = Math.max(depth,maxDepth(children) + 1);
}
return depth;
}
}
迭代遍歷:
class Solution { public int maxDepth(Node root) { Queue<Pair<Node,Integer>> stack = new LinkedList<>(); if(root != null){ stack.offer(new Pair(root,1)); } int max = 0; while(!stack.isEmpty()){ Pair<Node,Integer> node = stack.poll(); int value = node.getValue(); root = node.getKey(); if(root != null){ max = Math.max(max,value); for(Node temp : root.children){ stack.offer(new Pair(temp,value + 1)); } } } return max; } }