/*
 * 演算法 / Algorithm:
 * 遞迴 DFS：交換每個節點的 left/right，再翻轉兩棵子樹。
 * Recursive DFS: swap each node's left/right, then invert both subtrees.
 * 空節點是遞迴終止條件 / a null node is the base case.
 */

// LeetCode 預先定義 / LeetCode predefines:
// struct TreeNode { int val; TreeNode *left; TreeNode *right; ... };

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        // 空節點（nullptr）無需翻轉，直接回傳 / a null node needs no work — return it.
        // nullptr 是 C++ 的空指標字面值，比 C 的 NULL 更型別安全。
        // nullptr is C++'s typed null-pointer literal, safer than C's NULL.
        if (root == nullptr) {
            return nullptr;
        }

        // std::swap 是 STL 提供的工具，一行就能交換兩個變數的值，內部會用暫存變數。
        // std::swap is an STL helper that exchanges two values in one line (it uses a temp internally),
        // 這樣就不用自己手寫 temp，交換 root 的左右兩個指標。
        // so we avoid a manual temp; here we swap root's left and right pointers.
        std::swap(root->left, root->right);

        // 遞迴翻轉左子樹 / recursively invert the left subtree.
        invertTree(root->left);

        // 遞迴翻轉右子樹 / recursively invert the right subtree.
        invertTree(root->right);

        // 回傳翻轉後的根 / return the inverted root.
        return root;
    }
};
