๐๋ฌธ์
All Nodes Distance K in Binary Tree - LeetCode
๐์ด๋ค ์๊ณ ๋ฆฌ์ฆ?
1. ๋จ์ํ ๊ฑฐ๋ฆฌ๋ฅผ ์ด์ฉํด ํ๋จํ๊ฒ ๋๋ฏ๋ก, ์์ ๋ ธ๋๋ก๋ถํฐ ๋ถ๋ชจ ๋ ธ๋๋ฅผ ์ ๊ทผํ ์ ์์ด์ผ ํ๋ค. ๋ฐ๋ผ์ ๊ธฐ์กด์ ํธ๋ฆฌ ๊ตฌ์กฐ๋ก ๋์ด ์๋ ์๋ฃ๊ตฌ์กฐ๋ฅผ ๊ทธ๋ํ๋ก ๋ฐ๊ฟ์ค์ผํ๋ค.
2. ๊ทธ๋ํ๋ก ๋ฐ๊ฟ์ค ์๋ฃ ๊ตฌ์กฐ๋ฅผ BFS๋ฅผ ์ด์ฉํด ๊ฑฐ๋ฆฌ๊ฐ k์ธ ๋ ธ๋๋ฅผ ๋ชจ๋ ํ์ํ๋ค.
๐ป์ฝ๋
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
if k == 0:
return [target.val]
# 1. ํธ๋ฆฌ๋ฅผ ๊ทธ๋ํ๋ก ๋ง๋ค๊ธฐ
graph = collections.defaultdict(list)
deq = collections.deque([root])
# print('deq: ',deq)
while deq:
node = deq.popleft()
if node.left:
'''
์์ ๋
ธ๋์์ ๋ถ๋ชจ ๋
ธ๋, ๋ถ๋ชจ๋
ธ๋์์ ์์๋
ธ๋
์๋ฐฉํฅ์ผ๋ก ์ด์ด์ ธ ์์ด์ผ ํ๋ฏ๋ก ๋ชจ๋ ์ถ๊ฐ
'''
graph[node].append(node.left)
graph[node.left].append(node)
deq.append(node.left) # ์ฐ๊ฒฐ๋ ๋
ธ๋๋ฅผ ๊ณ์ํด์ ์ถ๊ฐํด์ฃผ๊ธฐ ์ํด
if node.right:
graph[node].append(node.right)
graph[node.right].append(node)
deq.append(node.right)
# 2. ๋ง๋ ๊ทธ๋ํ๋ฅผ ์ด์ฉํด bfsํ์
result = [] # ๊ฒฐ๊ณผ๋ฅผ ์ ์ฅํ ๋ฆฌ์คํธ
visited = set([target]) # ๋ฌดํ๋ฃจํ์ ๋น ์ง์ง ์๊ธฐ ์ํ ๋ฐฉ๋ฌธ ๋ฆฌ์คํธ
deq = collections.deque([(target, 0)])
while deq:
node, distance = deq.popleft()
if distance == k:
result.append(node.val)
else:
for edge in graph[node]:
if edge not in visited:
visited.add(edge)
deq.append((edge, distance+1))
return result
'Algorithm > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] 22. Generate Parentheses (ํ์ด์ฌ/python) (0) | 2023.09.01 |
---|---|
[LeetCode] 1395. Count Number of Teams (ํ์ด์ฌ/python) (0) | 2023.08.12 |
[LeetCode] 1061. Lexicographically Smallest Equivalent String (ํ์ด์ฌ/python) (0) | 2023.08.10 |
[LeetCode] 684. Redundant Connection (ํ์ด์ฌ/python) (0) | 2023.08.10 |
[LeetCode] 802. Find Eventual Safe States (ํ์ด์ฌ/python) (0) | 2023.08.07 |