JZ18 二叉树镜像
题目
操作给定的二叉树,将其变换为源二叉树的镜像。
思路
- 先遍历, 节点入栈, 再依次出栈调换左右节点
- 遍历的过程中调换左右节点
代码
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 先遍历, 入栈, 再调换左右节点
def Mirror(self, root):
# 判断传入节点是否为空
if root is None:
return None
line_node = self.printLevelNode(root)
# print(line_node)
while line_node:
tmp = line_node.pop()
if tmp.left or tmp.right:
tmp.left, tmp.right = tmp.right, tmp.left
return tmp
# 层次遍历二叉树, 被调用
def printLevelNode(self, root):
line_node = []
res = []
line_node.append(root)
while line_node:
tmp = line_node.pop(0)
res.append(tmp)
if tmp.left:
line_node.append(tmp.left)
if tmp.right:
line_node.append(tmp.right)
return res
# 层次遍历的过程中调换左右节点
def Mirror2(self, root):
if root is None:
return None
line_node = []
line_node.append(root)
while line_node:
tmp = line_node.pop(0)
if tmp.left:
line_node.append(tmp.left)
if tmp.right:
line_node.append(tmp.right)
# if tmp.left or tmp.right:
tmp.left, tmp.right = tmp.right, tmp.left
return root
# 递归遍历的过程中调换左右节点
def Mirror3(self, root):
if root is None:
return None
root.left, root.right = root.right, root.left
self.Mirror3(root.left)
self.Mirror3(root.right)
return root
if __name__ == '__main__':
node1 = TreeNode(8)
node2 = TreeNode(6)
node3 = TreeNode(10)
node4 = TreeNode(5)
node5 = TreeNode(7)
node6 = TreeNode(9)
node7 = TreeNode(11)
node1.left = node2
node1.right = node3
node2.left = node4
node2.right = node5
node3.left = node6
node3.right = node7
sl = Solution()
ls = sl.Mirror3(node1)
print(ls)
for i in sl.printLevelNode(ls):
print(i.val)