根据二叉树镜像的定义,考虑递归遍历(dfs)二叉树,交换每个节点的左 / 右子节点,即可生成二叉树的镜像。
def Mirror(self, pRoot):
# write code here
if not pRoot:
return pRoot
# 左右子树交换
pRoot.left, pRoot.right = pRoot.right, pRoot.left
# 递归左右子树
self.Mirror(pRoot.left)
self.Mirror(pRoot.right)
return pRoot
京公网安备 11010502036488号