题目
操作给定的二叉树,将其变换为源二叉树的镜像。
如下图所示:
解题思路
先交换根节点的两个子结点之后,我们注意到值为10、6的结点的子结点仍然保持不变,因此我们还需要交换这两个结点的左右子结点。做完这两次交换之后,我们已经遍历完所有的非叶结点。此时变换之后的树刚好就是原始树的镜像。交换示意图如下所示:
代码实现:
- C++代码:
/**
* 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 root;
}
TreeNode *tmp=root->left;
root->left = root->right;
root->right = tmp;
if(root->left){
mirrorTree(root->left);
}
if(root->right){
mirrorTree(root->right);
}
return root;
}
};
- Python代码:
# Definition for a binary tree node.
# 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 []
tmp = root.left
root.left = root.right
root.right = tmp
if root.left:
self.mirrorTree(root.left)
if root.right:
self.mirrorTree(root.right)
return root