解题思路:
递归法,只要root有一个子树不为空,就要swap一次,然后深入到子树中执行相同的操作
前条件:存在一个root
不变式:swap左右子树,递归
结束条件:root左右子树都为NULL
临界条件:root为NULL
// 编译错误
Line 23: return-statement with a value, in function returning 'void' [-fpermissive]
返回类型为void,用return NULL是肯定不对的
/**
* 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;
}
swapNode(root);
return root;
}
void swapNode(TreeNode* root){
if (root->left == NULL && root->right == NULL){
return;
}else{
TreeNode* temp;
temp = root->left;
root->left = root->right;
root->right = temp;
if (root->left != NULL){
invertTree(root->left);
}
if (root->right != NULL){
invertTree(root->right);
}
}
}
};