题目分析:
直接递归即可,代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root==NULL){
return NULL; //如果是空节点,那么返回NULL
}
swap(root->left,root->right); //否则交换该节点的左右孩子
invertTree(root->left); //递归处理左子树
invertTree(root->right); //递归处理右子树
return root; //返回
}
};