[LeetCode] 1008. Construct Binary Search Tree from Preorder Traversal

Updated:

1008. Construct Binary Search Tree from Preorder Traversal

์–ด๋–ค ํŠธ๋ฆฌ๋ฅผ ์„ ์œ„์ˆœํšŒ๋กœ ๋Œ์•˜์„ ๊ฒฝ์šฐ์˜ ๋ฐฉ๋ฌธ ์ˆœ์„œ๊ฐ€ ๋‹ด๊ธด ๋ฐฐ์—ด์ด Input ์œผ๋กœ ์ฃผ์–ด์ง„๋‹ค.

์ด๋•Œ ์ด Input ๊ฐ’์„ ๊ฐ€์ง€๊ณ  ์ด์ง„ ํƒ์ƒ‰ ํŠธ๋ฆฌ๋ฅผ ๋งŒ๋“œ๋Š” ๋ฌธ์ œ์ด๋‹ค. ์™œ ๊ตณ์ด ์„ ์œ„์ˆœํšŒ๋กœ ๋ฐฉ๋ฌธ ํ•œ ์ˆœ์„œ๋ฅผ ์คฌ๋Š”์ง€๋Š” ์•„์ง ์ž˜ ๋ชจ๋ฅด๊ฒ ๋‹ค..

๋ฃจํŠธ๋…ธ๋“œ๋ฅผ ์•Œ๊ฒŒ ํ•˜๊ธฐ ์œ„ํ•จ์ธ๊ฐ€.. ์–ด์จŒ๋“  ์„ ์œ„์ˆœํšŒ๋Š” ๋ฃจํŠธ๋ฅผ ๋จผ์ € ๋ฐฉ๋ฌธํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋ฐฐ์—ด์—์„œ index ๊ฐ€ 0 ์ธ ๊ฐ’์„ ๋ฃจํŠธ๋…ธ๋“œ๋กœ ์‚ผ์œผ๋ฉด ๋œ๋‹ค.

๊ทธ๋Ÿฌ๋‹ˆ๊นŒ ๊ทธ๋ƒฅ [8, 5, 1, 7, 10, 12] ์ˆœ์„œ๋กœ ์ด์ง„ ํƒ์ƒ‰ํŠธ๋ฆฌ๋ฅผ ๋งŒ๋“ค๋ฉด ์ •๋‹ต์ด๋‹ค.

์™œ ์„ ์œ„์ˆœํšŒ๋กœ ๋Œ์•˜์„ ๊ฒฝ์šฐ๋ฅผ Input ์œผ๋กœ ์ฃผ์—ˆ์„๊นŒ.. ๋‚ด๊ฐ€ ๋†“์นœ ๋ฌด์–ธ๊ฐ€๊ฐ€ ์žˆ๋‚˜.. ์ œ์•ฝ์กฐ๊ฑด์ด ์žˆ๋Š”๊ฑด๊ฐ€..


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 bstFromPreorder(self, preorder: List[int]) -> TreeNode:
		root = TreeNode(preorder[0])

		def make_BST(root, val):
			cur_node = root

			while True:
				if val < cur_node.val:
					if cur_node.left:
						cur_node = cur_node.left
					else:
						cur_node.left = TreeNode(val)
						break

				else:
					if cur_node.right:
						cur_node = cur_node.right
					else:
						cur_node.right = TreeNode(val)
						break

		for val in preorder[1:]:
			make_BST(root, val)

		return root

Categories:

Updated:

Leave a comment