forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChaedie.py
More file actions
32 lines (23 loc) ยท 778 Bytes
/
Chaedie.py
File metadata and controls
32 lines (23 loc) ยท 778 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
31
32
"""
ํ๋ฒ์ ํ์ง ๋ชปํด ๋ค์ ํ์ด๋ณผ ์์ ์
๋๋ค.
Solution:
1) oldToNew ๋ผ๋ dict ๋ฅผ ๋ง๋ค์ด ๋ฌดํ๋ฃจํ๋ฅผ ๋ฐฉ์งํฉ๋๋ค.
2) newNode = Node(node.val), newNode.neighbors.append(dfs(nei)) ๋ฅผ ํตํด clone์ ๊ตฌํํฉ๋๋ค.
์ ์ V, ๊ฐ์ E
Time: O(V + E)
Space: O(V + E)
"""
class Solution:
def cloneGraph(self, root: Optional["Node"]) -> Optional["Node"]:
if not root:
return None
oldToNew = {}
def dfs(node):
if node in oldToNew:
return oldToNew[node]
newNode = Node(node.val)
oldToNew[node] = newNode
for nei in node.neighbors:
newNode.neighbors.append(dfs(nei))
return newNode
return dfs(root)