题目描述
输入一个二叉树,将它变换为它的镜像。
样例:
思路
观察后可发现,镜像后的二叉树就是把所有节点的左右儿子交换。具体实现步骤如下:
1、用递归的方法遍历二叉树的节点,非叶子节点交换该节点的左右儿子
2、遇到叶子节点则返回
代码实现
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def mirror(self, root):
"""
:type root: TreeNode
:rtype: void
"""
if not root:
return
root.left, root.right = root.right, root.left
self.mirror(root.left)
self.mirror(root.right)