226反转二叉树

核心在于,如果一个节点的子节点的子节点都已经交换顺序了,那么就交换该节点的左右子节点。

#include<iostream>
#include<queue>
#include<vector>
using namespace std;
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (root == nullptr) {
            return nullptr;
        }
        TreeNode* left = invertTree(root->left);
        TreeNode* right = invertTree(root->right);
        root->left = right;
        root->right = left;
        return root;
    }
};
void print(TreeNode* a) {
    if(a != nullptr){
        cout << a->val;
        print(a->left);
        print(a->right);
    }
}
int main() {
    Solution test;
    TreeNode* c = new TreeNode(3);
    TreeNode* b = new TreeNode(2);
    TreeNode* a = new TreeNode(1,c, b);
    print(a);
    TreeNode* ans = test.invertTree(a);
    print(ans);
}
上一篇:AtCoder Beginner Contest 226


下一篇:AtCoder Beginner Contest 226(A-G)