【力扣日记】面试题27:二叉树的镜像 | 递归

题目描述

请完成一个函数,输入一个二叉树,该函数输出它的镜像。

例如输入:
     4
   /   \
  2     7
 / \   / \
1   3 6   9
镜像输出:
     4
   /   \
  7     2
 / \   / \
9   6 3   1

算法思路

和最小高度树一样卡了一段时间的题,今天回过头来写,做出了最小高度树,然后轻松写出了这个。

class Solution:
    def mirrorTree(self, root: TreeNode) -> TreeNode:
        def helper(root):
            if not root:return 
            r=TreeNode(root.val)
            r.left=helper(root.right)
            r.right=helper(root.left)
            return r
        return helper(root)

执行用时 :36 ms, 在所有 Python3 提交中击败了81.26%的用户
内存消耗 :13.6 MB, 在所有 Python3 提交中击败了100.00%的用户

发布了317 篇原创文章 · 获赞 44 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Heart_for_Ling/article/details/105577326
今日推荐