今天的題目為111.Minimum Depth of Binary Tree,他再叫我們找出二元樹的最小深度呦。
以下是程式碼與解說:
class Solution {
public int minDepth(TreeNode root) {
// 若根節點為 null,代表空樹,最小深度為 0
if(root == null) return 0;
// 找最短路徑
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root); // 將根節點加入佇列
int depth = 1; // 初始深度為 1(根節點)
// 當佇列不為空時,持續進行層級遍歷
while(!queue.isEmpty()){
int size = queue.size(); // 當前層的節點數量
// 遍歷當前層的所有節點
for(int i = 0; i < size; i++){
TreeNode currentNode = queue.poll(); // 取出佇列中的節點
// 若該節點是葉子節點(無左右子節點),回傳目前深度
if(currentNode.left == null && currentNode.right == null){
return depth;
}
// 若左子節點存在,加入佇列
if(currentNode.left != null) queue.offer(currentNode.left);
// 若右子節點存在,加入佇列
if(currentNode.right != null) queue.offer(currentNode.right);
}
// 每完成一層,深度加一
depth++;
}
return depth;
}
}