剑指offer 二叉树的镜像

二叉树的镜像

题目

操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:

1
2
3
4
5
6
7
8
9
10
11
12
二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5

方法

方法1:递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# -*- coding:utf-8 -*-
# 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)
return root

方法2:迭代

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 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
stack=[root]
while stack:
node=stack.pop()
if not node:
continue
node.left,node.right=node.right,node.left
stack.append(node.right)
stack.append(node.left)

return root
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# -*- coding:utf-8 -*-
# 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

stack=[root]
while stack:
node=stack.pop()
if node:
node.left,node.right=node.right,node.left
stack.append(node.right)
stack.append(node.left)

```

```python
# -*- coding:utf-8 -*-
# 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

stack=[]
node=root
while node or stack:
while node:
node.left,node.right=node.right,node.left # 此两句代码不能交换顺序
stack.append(node.right)
node=node.left
node=stack.pop()
return root