iT邦幫忙

2024 iThome 鐵人賽

DAY 6
0
佛心分享-刷題不只是刷題

Java刷題A:Leetcode Top 100 Liked系列 第 6

Day6 Binary Tree二元樹 - 題目1:226. Invert Binary Tree

  • 分享至 

  • xImage
  •  

原文題目
Given the root of a binary tree, invert the tree, and return its root.

題目摘要

  1. 給定一棵二元樹的根節點,將整棵樹的左右子樹進行反轉,並回傳新的根節點。
  2. 輸入:一個二元樹的根節點 root
  3. 輸出:反轉後的二元樹的根節點

Example 1:
https://ithelp.ithome.com.tw/upload/images/20240919/20168780XYr6BlqgdA.jpg

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

Example 2:
https://ithelp.ithome.com.tw/upload/images/20240919/20168780C7Dl1r5dGP.jpg

Input: root = [2,1,3]
Output: [2,3,1]

Example 3:

Input: root = []
Output: []

解題思路

  1. 初步檢查:
    如果當前節點為 null,這意味著已經到達樹的末端或者樹是空的,因此直接返回 null

  2. 反轉當前節點的左右子樹:

    • 使用輔助變數 temp 來存儲當前節點的左子樹。
    • 將當前節點的左子樹設為右子樹。
    • 將當前節點的右子樹設為 temp(即原來的左子樹)。
  3. 遞迴處理子樹:
    遞迴使用 invertTree 方法分別對反轉後的左子樹和右子樹進行相同的操作。

  4. 回傳反轉後的根節點:
    完成當前節點及其子樹的反轉後,則回傳反轉後的根節點。

程式碼

class Solution {
    public TreeNode invertTree(TreeNode root) {
        //如果當前節點為null則返回
        if (root == null) {
            return null;
        }
        //設立temp來輔助左、右子樹的質做交換
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        
        invertTree(root.left); //遞迴反轉左子樹
        invertTree(root.right); //遞迴反轉右子樹
        
        return root; //反轉完成則回傳反轉後的根節點       
    }
}

結論
我覺得這題的解法非常直觀,只需要進行左右子樹的交換,再透過遞迴遍歷整棵樹,就能得到正解,過程中只要確保終止條件和左右子樹的交換順序無誤,整個流程就能順利執行啦!


上一篇
Day5 Binary Tree二元樹 - 概念介紹
下一篇
Day7 Binary Tree二元樹 - 題目2:94. Binary Tree Inorder Traversal
系列文
Java刷題A:Leetcode Top 100 Liked13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言