Fetch the repository succeeded.
This action will force synchronization from 陌溪/LearningNotes, which will overwrite any changes that you have made since you forked the repository, and can not be recovered!!!
Synchronous operation will process in the background and will refresh the page when finishing processing. Please be patient.
https://www.nowcoder.com/practice/564f4c26aa584921bc75623e48ca3011
操作给定的二叉树,将其变换为源二叉树的镜像。
二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
我们就对每个节点的左右子树进行交换即可,也就是需要使用一个temp变量来存储交换的节点。然后在重复它的左子树和右子树
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回镜像树的根节点
def Mirror(self, root):
if root == None:
return None
# 处理左子树
temp = root.left
root.left = root.right
root.right = temp
self.Mirror(root.left)
self.Mirror(root.right)
利用栈(或队列)遍历树的所有节点 node ,并交换每个node 的左 / 右子节点。
算法流程:
图示:
代码:
class Solution:
def Mirror(self, root):
if root == None:
return None
stack = [root]
while stack:
node = stack.pop()
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
node.right,node.left = node.left, node.right
return root
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。