''' 题目描述 操作给定的二叉树,将其变换为源二叉树的镜像。 输入描述: 二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \ 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 if root is None: return None curr_list=[] curr_list.append(root) while curr_list: curr=curr_list.pop(0) #则交换当前节点的左孩子和右孩子节点 temp=curr.left curr.left=curr.right curr.right=temp if curr.right is not None: curr_list.append(curr.right) if curr.left is not None: curr_list.append(curr.left) 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: return root node = root.left root.left = root.right root.right = node self.Mirror(root.left) self.Mirror(root.right) return root
二叉树的镜像
最新推荐文章于 2021-02-21 06:45:37 发布