iT邦幫忙

2025 iThome 鐵人賽

DAY 0
0
自我挑戰組

Leetcode30天挑戰系列 第 8

Day8-Binary Tree Level Order Traversal II

  • 分享至 

  • xImage
  •  

今天的題目為107.Binary Tree Level Order Traversal II,這題是在考驗我們把節點讀出來,但是是由下往上讀到root,並且先讀左邊的元素。

以下是程式碼與解說:

class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        // 建立一個 LinkedList 來儲存最終結果(由底層到頂層)
        List<List<Integer>> result = new LinkedList<>();
        
        // 若根節點為 null,直接回傳空結果
        if(root == null) return result;

        // 使用 Queue 來進行 BFS(廣度優先搜尋)
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root); // 將根節點加入佇列

        // 當佇列不為空時,持續進行層級遍歷
        while(!queue.isEmpty()){
            int levelSize = queue.size(); // 當前層的節點數量
            List<Integer> levelList = new ArrayList<>(); // 儲存當前層的節點值

            // 遍歷當前層的所有節點
            for(int i = 0; i < levelSize; i++){
                TreeNode currentNode = queue.poll(); // 取出佇列中的節點
                levelList.add(currentNode.val); // 加入該節點的值到當前層列表

                // 若左子節點存在,加入佇列
                if(currentNode.left != null) queue.offer(currentNode.left);
                // 若右子節點存在,加入佇列
                if(currentNode.right != null) queue.offer(currentNode.right);
            }
            
            result.add(0, levelList); 
            // 將當前層的結果插入到最前面(達成由底層到頂層的順序)
            
        }

        return result;// 回傳最終結果
    }
}

上一篇
Day7-Construct Binary Tree from Inorder and Postorder Traversal
下一篇
Day9-Convert Sorted Array to Binary Search Tree
系列文
Leetcode30天挑戰15
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言