forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyyyyyyyyyKim.py
More file actions
30 lines (24 loc) ยท 891 Bytes
/
yyyyyyyyyKim.py
File metadata and controls
30 lines (24 loc) ยท 891 Bytes
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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
# ์ด์งํธ๋ฆฌ ๋ค์ง๊ธฐ(์ข์ฐ๋ฐ์ )
# DFS(stack์ด์ฉ, ์๊ฐ๋ณต์ก๋ O(n), ๊ณต๊ฐ๋ณต์ก๋ O(n))
if not root:
return None
stack = [root]
while stack:
# ์คํ ๋งจ๋ค์ ์๋ ๊ฑฐ popํด์ ๊บผ๋ด๊ธฐ
node = stack.pop()
# ์์ ๋
ธ๋ ๊ตํ
node.left, node.right = node.right, node.left
# ์์ ๋
ธ๋๋ฅผ ์คํ์ ์ถ๊ฐ
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return root