解題思路
先序遍歷
首先判斷左右節點是否都不爲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* mirrorTree(TreeNode* root) {
if (root == NULL) return NULL;//爲空不進行交換
else if(root->left!=NULL||root->right!=NULL)//左節點和右節點都不爲null時就進行交換
{
TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
if(root->left!=NULL) mirrorTree(root->left);//左子樹存在則進行鏡像
if(root->right!=NULL) mirrorTree(root->right);//右子樹存在則進行鏡像
}
return root;
}
};