FollowMee 发表于5个月前

• 发表于 5个月前
• 阅读 1
• 收藏 0
• 评论 0

# 二叉树的镜像

• 递归方法
``````# -*- 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 or (not root.left and not root.right):
return root
root.left, root.right = root.right, root.left
if root.left:
self.Mirror(root.left)
if root.right:
self.Mirror(root.right)
return root``````
• 非递归方法，二叉树的层次遍历
``````# -*- 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 or (not root.left and not root.right):
return root
temp = []
temp.append(root)
while(temp):
node = temp.pop()
if (node.left or node.right):
node.left, node.right = node.right, node.left
if (node.left):
temp.append(node.left)
if (node.right):
temp.append(node.right)
return root``````

×