/**
* 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) {
TreeNode *temp;
if(root){
temp = root->right;
root->right = root->left;
root->left = temp;
invertTree(root->left);
invertTree(root->right);
}
return root;
}
};
这题和遍历类似,遍历的时候先把左右子树交换,就得出反转的二叉树。