题目
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
思路
思路一:递归交换左右节点。
思路二:
利用栈(或队列)遍历树的所有节点 nodenode ,并交换每个 nodenode 的左 / 右子节点。
算法流程:
特例处理: 当 rootroot 为空时,直接返回 nullnull ;
初始化: 栈(或队列),本文用栈,并加入根节点 rootroot 。
循环交换: 当栈 stackstack 为空时跳出;
出栈: 记为 nodenode ;
添加子节点: 将 nodenode 左和右子节点入栈;
交换: 交换 nodenode 的左 / 右子节点。
返回值: 返回根节点 rootroot 。
代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
if root is None:
return
tmp = root.left
root.left = self.mirrorTree(root.right)
root.right = self.mirrorTree(tmp)
return root
if not root: return
stack = [root]
while stack:
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
作者:jyd
链接:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/solution/mian-shi-ti-27-er-cha-shu-de-jing-xiang-di-gui-fu-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
pythonic的写法
就是不断递归交换左右节点的值
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
if root is None:
return
root.left, root.right = self.mirrorTree(root.right), self.mirrorTree(root.left)
return root