完成一个函数,输入一个二叉树,输出它的镜像
例如输入:
输出它的镜像:
解决方法:将每个节点的左右子节点交换
python实现:
class TreeNode:
def _init_(self,x):
self.val = x
self.left = None
self.right = None
class Solution:
def mirrorTree(self,root->TreeNode)->TreeNode:
if not root:
return None
self.left,self.right = self.mirrorTree(root.right),self.mirrorTree(root.left)
return root
C++实现:
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
}
class Solution{
public:
TreeNode* mirrorTree(TreeNode* root) {
if(root != NULL){
if(root->left != NULL || root->right != NULL){
TreeNode* tmp = root->left;
root->left = root->right;
root->right = tmp;
mirrorTree(root->left);
mirrorTree(root->right);
}
}
return root
};