请完成一个函数,输入一棵二叉树,该函数输出它的镜像。
class Solution:
def mirror_recursively(self, root):
if root:
root.left, root.right = root.right, root.left
self.mirror(root.left)
self.mirror(root.right)
return root
循环版
class Solution:
def mirror(self, root):
if not root:
return root
stack = [root]
while stack:
node = stack.pop()
node.left, node.right = node.right, node.left
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return root
(最近更新:2019年07月24日)
本文介绍了一种实现二叉树镜像的算法,通过递归和迭代两种方式,详细展示了如何将一棵二叉树转换为其镜像。适用于数据结构与算法的学习与实践。
218

被折叠的 条评论
为什么被折叠?



