# 第27题：Leetcode226: Invert Binary Tree反转二叉树

     4
/   \
2     7
/ \   / \
1   3 6   9

     4
/   \
7     2
/ \   / \
9   6 3   1

思路

auto tmp = invertTree(root->left);

/**
* 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 root;
auto temp=invertTree(root->left);
root->left=invertTree(root->right);
root->right=temp;
return root;
}
};

/**
* 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 root;
TreeNode *tmp = root->left;
root->left = root->right;
root->right = tmp;
if(root->left)invertTree(root->left);
if(root->right)invertTree(root->right);
return root;

}
};

### 解三：

/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
void Mirror(TreeNode *pRoot) {

if(!pRoot)
return;
if(!pRoot->left&&!pRoot->right)
return;

auto temp=pRoot->left;
pRoot->left=pRoot->right;
pRoot->right=temp;

if(pRoot->left)
Mirror(pRoot->left);
if(pRoot->right)
Mirror(pRoot->right);

}
};

posted @ 2019-02-07 19:26  lightmare  阅读(42)  评论(0编辑  收藏