forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwozlsla.py
More file actions
44 lines (31 loc) ยท 1.11 KB
/
wozlsla.py
File metadata and controls
44 lines (31 loc) ยท 1.11 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
from typing import Optional
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
"""
- L/R ๋
ธ๋์ ์์น ๋ณ๊ฒฝ ๋ฐ๋ณต - ์ฌ๊ท/๋ฐ๋ณต
- ํธ๋ฆฌ ์ํ: ๋ฐ๋ณต๋ฌธ->BFS(Queue)
1. ํ์ ํ์ฌ ๋
ธ๋ ์ถ๊ฐ
2. ํ์์ ๋
ธ๋ ๊บผ๋
3. ๊บผ๋ธ ๋
ธ๋์ ์ผ์ชฝ<->์ค๋ฅธ์ชฝ ์์ ์์น ๋ณ๊ฒฝ
4. ์์น๋ฅผ ๋ฐ๊พผ ์์ ๋
ธ๋๋ค์ด ์๋ค๋ฉด, ๋ค์ ํ์ ์ฝ์
5. ํ๊ฐ ๋น ๋๊น์ง ๋ฐ๋ณต
"""
from collections import deque
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return
que = deque([root])
while que:
node = que.popleft()
# ๋
ธ๋์ ์ผ์ชฝ๊ณผ ์ค๋ฅธ์ชฝ ์์ ๊ตํ
node.left, node.right = node.right, node.left
# ๋ฐ๊พผ ์์ ๋
ธ๋๋ค์ด ์์ผ๋ฉด ํ์ ์ถ๊ฐ (ํ๋๋ง ์๊ฑฐ๋ ์๋ ๊ฒฝ์ฐ ์ฒ๋ฆฌ)
if node.left:
que.append(node.left)
if node.right:
que.append(node.right)
return root