-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy path226.翻转二叉树.py
64 lines (60 loc) · 1.36 KB
/
226.翻转二叉树.py
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# 翻转一棵二叉树。
#
# 示例:
#
# 输入:
#
# 4
# / \
# 2 7
# / \ / \
# 1 3 6 9
# 输出:
#
# 4
# / \
# 7 2
# / \ / \
# 9 6 3 1
# 方法一:递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return
left = self.invertTree(root.left)
right = self.invertTree(root.right)
root.left = right
root.right = left
return root
# time:O(N)
# space:O(N)
# 方法二:迭代
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:return
queue = deque([root,])
while queue:
cur = queue.popleft()
tmp = cur.left
cur.left = cur.right
cur.right = tmp
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
return root
# time:O(N)
# space:O(N)