#include <bits/stdc++.h>
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 *pTemp = root->left;
root->left = root->right;
root->right = pTemp;
//遍历左子树
invertTree(root->left);
invertTree(root->right);
return root;
}
};
package main
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func invertTree(root *TreeNode) *TreeNode {
//结束条件
if root == nil {
return nil
}
//翻转左右节点
temp := root.Left
root.Left = root.Right
root.Right = temp
//翻转左子树
invertTree(root.Left)
//翻转右子树
invertTree(root.Right)
return root
}