题目叙述
递归方法
时间久,但是占用内存少
// An highlighted block
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
if not root:
return None
root.left, root.right = root.right, root.left
if root.left:
self.mirrorTree(root.left)
if root.right:
self.mirrorTree(root.right)
return root
非递归方法
我本来一直觉得这个和二叉树的层次遍历类似,但是没想出好的方法,这里看到了一个很好的题解
// An highlighted block
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
stack = [root]
while len(stack)>0:
node = stack.pop()
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
node.left, node.right = node.right, node.left
return root
继续加油!