第2章 面试需要的基础知识
第3章 高质量的代码
第4章 解决面试题的思路
面试题27 :二叉树的镜像
第5章 优化时间和空间效率
第6章 面试中的各项能力
第7章 两个面试案例
题目描述
牛客网
操作给定的二叉树,将其变换为源二叉树的镜像。
解题思路
前序遍历树的每个节点,如果节点有子节点,则交换两个子节点。遍历完成就得到了树的镜像。
实战
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回镜像树的根节点
def Mirror(self, root):
# write code here
if not root:
return
root.left, root.right = root.right, root.left
self.Mirror(root.left)
self.Mirror(root.right)
原题:Leetcdoe 226