题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
思路:
这道题用递归做最合适不过,其思路很简单,既然是递归那函数的开始一定有跳出递归的条件,条件就是当遍历到树节点为空时,就跳出递归。剩下的就是交换根节点左右子节点了,在交换完毕之后要进入到子节点的子树中对子树再进行左右节点的交换,如此循环下去,代码如下:
Solution:
Python
# -*- 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 is None:
return root
root.left,root.right = root.right,root.left
self.Mirror(root.left)
self.Mirror(root.right)