Invert Binary Tree

1,题目要求

Invert a binary tree.

翻转一颗二叉树。

Invert Binary Tree

2,题目思路

对于这道树的题目,题目要求是将一个二叉树翻转。

我们可以从树的翻转形式看出,这种翻转是递归的,即每个子树都发生了翻转。

因此,对于这道题,我们也使用递归的方法,依次两两交换节点即可。

3,代码实现

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root == nullptr)
            return nullptr;
        
        swap(root->left, root->right);
        invertTree(root->left);
        invertTree(root->right);
        
        return root;
    }
};