题目:
Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1
分析:分析左右子树情况,利用递归
代码:
/**
* 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!=NULL)
{
if(root->left==NULL&&root->right==NULL)
{
return root;
}
else if(root->left!=NULL&&root->right==NULL)
{
root->right=invertTree(root->left);
root->left=NULL;
}
else if(root->left==NULL&&root->right!=NULL)
{
root->left=invertTree(root->right);
root->right=NULL;
}
else
{
temp=root->right;
root->right=invertTree(root->left);
root->left=invertTree(temp);
//res->val=root->val;
}
}
return root;
}
};