题目描述:
操作给定的二叉树,将其变换为源二叉树的镜像。
如下图所示:
解题思路:
先交换根节点的两个子结点之后,我们注意到值为10、6的结点的子结点仍然保持不变,因此我们还需要交换这两个结点的左右子结点。做完这两次交换之后,我们已经遍历完所有的非叶结点。此时变换之后的树刚好就是原始树的镜像。交换示意图如下所示:
举例:
代码实现(c )
/*
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 == null) || (proot->left == null && proot->right == null)){
return;
}
//交换根节点的左右结点
treenode *ptemp = proot->left;
proot->left = proot->right;
proot->right = ptemp;
//递归左子树
if(proot->left){
mirror(proot->left);
}
//递归右子树
if(proot->right){
mirror(proot->right);
}
}
};
代码实现(java)
/**
public class treenode {
int val = 0;
treenode left = null;
treenode right = null;
public treenode(int val) {
this.val = val;
}
}
*/
public class solution {
public void mirror(treenode root) {
//当前节点为空,直接返回
if(root == null)
return;
//当前节点没有叶子节点,直接返回
if(root.left == null && root.right == null)
return;
treenode temp = root.left;
root.left = root.right;
root.right = temp;
//递归交换叶子节点
if(root.left != null)
mirror(root.left);
if(root.right != null)
mirror(root.right);
}
}
代码实现(python2.7)
# -*- coding:utf-8 -*-
# class treenode:
# def __init__(self, x):
# self.val = x
# self.left = none
# self.right = none
class solution:
# 返回镜像树的根节点
def mirror(self, root):
# write code here
if (root == none or (root.left == none and root.right == none)):
return none
tmp = root.left
root.left = root.right
root.right = tmp
if root.left:
self.mirror(root.left)
if root.right:
self.mirror(root.right)