[LeetCode] 1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree

Updated:

Find a Corresponding Node of a Binary Tree in a Clone of That Tree

๋ฌธ์ œ๋ฅผ ์ฝ๊ณ  ๋˜์ž‰ ? ํ–ˆ๋‹ค. ๋ญ”๊ฐ€ origianl tree, cloned tree ํ•˜๋ฉด์„œ ์—„์ฒญ ๊ฑฐ์ฐฝํ•ด๋ณด์˜€๋‹ค.. ๊ทธ๋Ÿฐ๋ฐ ๊ทธ๋ƒฅ ๋…ธ๋“œ ์ฐพ๊ธฐ ๋ฌธ์ œ์˜€๋‹ค.

์™œ ์›๋ณธ, ๋ณต์ œ ํŠธ๋ฆฌ๋ฅผ ๊ตฌ๋ถ„์ง€์€ ๊ฒƒ ์ผ๊นŒ.. ๋ฌธ์ œ ํ’€์ด์— ์•„๋ฌด๋Ÿฐ ์ƒ๊ด€์ด ์—†๋‹ค.. ๊ทธ๋ƒฅ target ๋…ธ๋“œ ์ฐพ์•„๊ฐ€๋ฉด ๊ทธ๋งŒ..

๊ทธ๋ž˜์„œ BFS ๋ฅผ ํ†ตํ•ด ์ฐพ์•„๊ฐ€๋Š” ๋ฐฉ์‹์œผ๋กœ ์ฝ”๋”ฉ ํ–ˆ๋‹ค.


from collections import deque


class TreeNode:
	def __init__(self, x):
		self.val = x
		self.left = None
		self.right = None

class Solution:
	def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
		queue = deque()
		queue.append(cloned)
		while queue:
			node = queue.popleft()
			if node.val == target.val:
				return node

			if node.left:
				queue.append(node.left)
			if node.right:
				queue.append(node.right)

๊ทธ๋Ÿฐ๋ฐ ํ’€๊ณ ๋ณด๋‹ˆ ๋ฌธ์ œ์— ์ข‹์•„์š” ๋ณด๋‹ค ์‹ซ์–ด์š”๊ฐ€ ๋” ๋งŽ์•˜๋˜ ๋ฌธ์ œ์˜€๋‹ค. ๋‹ค๋ฅธ ์‚ฌ๋žŒ๋“ค๋„ ๋ณด๊ณ  ์›ƒ๊ฒผ๋‚˜๋ณด๋‹ค!


Categories:

Updated:

Leave a comment