forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdusunax.py
More file actions
65 lines (48 loc) · 1.33 KB
/
dusunax.py
File metadata and controls
65 lines (48 loc) · 1.33 KB
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
65
'''
# 226. Invert Binary Tree
switch left and right child of each node
## TC: O(N)
visit each node once
## SC: O(h)
h is height of tree
- best case: O(logN), balanced tree
- worst case: O(N), skewed tree
'''
class Solution:
'''
DFS
'''
def invertTreeRecursive(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
'''
BFS
- 직관적인 stack 풀이
'''
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
stack = [root]
while stack:
node = stack.pop()
if not node:
continue
node.left, node.right = node.right, node.left
stack.append(node.left)
stack.append(node.right)
return root
'''
- 참고용 deque 풀이
'''
def invertTreeDeque(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
dq = deque([root])
while dq:
node = dq.popleft()
if not node:
continue
node.left, node.right = node.right, node.left
dq.append(node.left)
dq.append(node.right)
return root