前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 剑指 Offer 27. 二叉树的镜像

LeetCode 剑指 Offer 27. 二叉树的镜像

原创
作者头像
freesan44
修改2021-09-18 14:58:01
2290
修改2021-09-18 14:58:01
举报
文章被收录于专栏:freesan44

## 题目地址(27. 二叉树的镜像)

https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/

## 题目描述

```

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

例如输入:

     4

   /   \

  2     7

 / \   / \

1   3 6   9

镜像输出:

     4

   /   \

  7     2

 / \   / \

9   6 3   1

 

示例 1:

输入:root = [4,2,7,1,3,6,9]

输出:[4,7,2,9,6,3,1]

 

限制:

0 <= 节点个数 <= 1000

注意:本题与主站 226 题相同:https://leetcode-cn.com/problems/invert-binary-tree/

```

## 思路

用递归实现

## 代码

- 语言支持:Python3

Python3 Code:

```python

# 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:

node = self.swap(root)

return node

def swap(self, node: TreeNode) -> TreeNode:

if node == None:

return None

node.left, node.right = node.right, node.left

node.left = self.swap(node.left)

node.right = self.swap(node.right)

return node

```

**复杂度分析**

令 n 为数组长度。

- 时间复杂度:$O(n)$

- 空间复杂度:$O(n)$

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档