递归法
1、判断是否为空,为空则返回
2、依次将每个节点的左右孩子交换
/**
* Definition for a binary tree node.
* 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==NULL){
return root;
}
else{
TreeNode* temp=root->left;//定义临时变量存左节点
root->left=root->right;//左节点的值变成右节点
root->right=temp;//右节点的值变成左节点
invertTree(root->left);//递归
invertTree(root->right);
}
return root;
}
};