题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
二叉树的镜像定义:
源二叉树 镜像二叉树
8 8
/ \ / \
6 10 10 6
/ \ / \ / \ / \
5 7 9 11 11 9 7 5
初始代码:
# -*- 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
思路:
二叉树的常见操作就是递归,不妨从递归的思路来思考此题
# -*- 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 not root: # 终止递归的条件
return root
node = root.left # node中间键 指向根节点left
root.left = root.right # 左子节点 = 右字节点
root.right = node # 右子节点指向左子节点
self.Mirror(root.left) # 递归左子节点,循环执行 节点交换操作
self.Mirror(root.right) # # 递归右子节点,循环执行 节点交换操作
return root # 返回主节点root