[LeetCode] 1305. All Elements in Two Binary Search Trees

Updated:

1305. All Elements in Two Binary Search Trees

MergeBST

์ด์ง„ ํƒ์ƒ‰ ํŠธ๋ฆฌ ๋‘ ๊ฐœ๋ฅผ ์ˆœํšŒํ•ด์„œ ์ •๋ ฌ ๋œ ๊ฐ๊ฐ์˜ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋งŒ๋“  ๋’ค ๋‘ ๋ฆฌ์ŠคํŠธ๋ฅผ ์˜ค๋ฆ„์ฐจ์ˆœ ํ˜•ํƒœ๋กœ ํ•ฉ์น˜๋ฉด ๋˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•์€ ์•„์ฃผ ๋‹ค์–‘ํ•˜๋‹ค.

ํŠธ๋ฆฌ๋ฅผ ์•„๋ฌด๋ ‡๊ฒŒ๋‚˜ ์ˆœํšŒ ํ•ด์„œ ์–ป์€ ๋ฆฌ์ŠคํŠธ๋ฅผ ํ•ฉ์นœ ๋’ค ์ •๋ ฌ์„ ํ•ด๋„ ๋˜๊ณ ..

ํŠธ๋ฆฌ๋ฅผ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ˆœํšŒํ•ด์„œ ์–ป์€ ๋ฆฌ์ŠคํŠธ๋ฅผ ํ•ฉ์นœ ๋’ค ์ •๋ ฌ์„ ํ•ด๋„ ๋˜๊ณ ..

ํŠธ๋ฆฌ๋ฅผ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ˆœํšŒํ•ด์„œ ์–ป์€ ๋ฆฌ์ŠคํŠธ๋ฅผ ํˆฌ ํฌ์ธํ„ฐ ์•Œ๊ณ ๋ฆฌ์ฆ˜์œผ๋กœ ํ•ฉ์ณ๋„ ๋œ๋‹ค..

๋ฌผ๋ก  ์•„๋ฌด๋ ‡๊ฒŒ๋‚˜ ์ˆœํšŒํ•ด์„œ ์–ป์€ ๋ฆฌ์ŠคํŠธ๋ฅผ ํ•ฉ์นœ ๋’ค ์ •๋ ฌ์„ ํ•˜๋Š”๊ฒŒ ๊ฐ€์žฅ ์‰ฝ๋‹ค.

๊ทธ๋ž˜๋„ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ๋ฅผ ํ‘ธ๋Š”๊ฑฐ๋‹ˆ๊นŒ.. ํŠธ๋ฆฌ๋ฅผ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ˆœํšŒํ•ด์„œ ์–ป์€ ๋ฆฌ์ŠคํŠธ๋ฅผ ํˆฌ ํฌ์ธํ„ฐ ์•Œ๊ณ ๋ฆฌ์ฆ˜์œผ๋กœ ํ•ฉ์น˜๋Š” ๋ฐฉํ–ฅ์œผ๋กœ ํ’€์—ˆ๋‹ค.

์ด์ง„ ํƒ์ƒ‰ ํŠธ๋ฆฌ๋Š” ์ค‘์œ„์ˆœํšŒ๋ฅผ ํ•  ๊ฒฝ์šฐ ์ •๋ ฌ ๋œ ์ˆœ์„œ๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ๋‹ค !


from typing import List


# 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 make_sort_list(self, root):
		_list = []

		def in_order(root):
			if not root:
				return

			else:
				in_order(root.left)
				_list.append(root.val)
				in_order(root.right)

		in_order(root)
		return _list

	def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
		a = self.make_sort_list(root1)
		b = self.make_sort_list(root2)
		merge = []
		a_idx, b_idx = 0, 0

		while a_idx < len(a) and b_idx < len(b):
			if a[a_idx] >= b[b_idx]:
				merge.append(b[b_idx])
				b_idx += 1
			else:
				merge.append(a[a_idx])
				a_idx += 1

		while a_idx < len(a):
			merge.append(a[a_idx])
			a_idx += 1
		while b_idx < len(b):
			merge.append(b[b_idx])
			b_idx += 1

		return merge

Categories:

Updated:

Leave a comment