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