## 题目地址(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 删除。