题目描述:
操作给定的二叉树,将其变换为源二叉树的镜像。
解法一:
递归
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def Mirror(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 = []
stack.append(root)
while stack:
node = stack.pop(-1)
if node.left or node.right:
node.left, node.right =node.right, node.left
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return root