iT邦幫忙

2025 iThome 鐵人賽

DAY 0
0
自我挑戰組

Leetcode30天挑戰系列 第 12

Day12-Minimum Depth of Binary Tree

  • 分享至 

  • xImage
  •  

今天的題目為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;        
    }
}

上一篇
Day11-Balanced Binary Tree
下一篇
Day13-Path Sum
系列文
Leetcode30天挑戰15
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言