[LeetCode] 654. Maximum Binary Tree

Updated:

654. Maximum Binary Tree

์ฃผ์–ด์ง„ ์กฐ๊ฑด๋Œ€๋กœ ์ด์ง„ ํŠธ๋ฆฌ๋ฅผ ๊ตฌํ˜„ํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

  1. ๋ฃจํŠธ๋…ธ๋“œ๋Š” ํ•ด๋‹น ๋ฐฐ์—ด์˜ Max ๊ฐ’์„ ๊ฐ€์ง„๋‹ค.
  2. ์™ผ์ชฝ ์„œ๋ธŒ ํŠธ๋ฆฌ๋Š” ํ•ด๋‹น ๋ฐฐ์—ด์˜ Max ๊ฐ’ ๊ธฐ์ค€ ์™ผ์ชฝ ๋ฐฐ์—ด๋“ค๋กœ ์ด๋ฃจ์–ด์ง„๋‹ค.
  3. ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒ ํŠธ๋ฆฌ๋Š” ํ•ด๋‹น ๋ฐฐ์—ด์˜ Max ๊ฐ’ ๊ธฐ์ค€ ์˜ค๋ฅธ์ชฝ ๋ฐฐ์—ด๋“ค๋กœ ์ด๋ฃจ์–ด์ง„๋‹ค.

[3, 2, 1, 6, 0, 5] ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค๋ฉด ๋ฃจํŠธ๋…ธ๋“œ์˜ ๊ฐ’์€ 6 ์ด ๋˜๊ณ  [3, 2, 1] ๋กœ ์™ผ์ชฝ ์„œ๋ธŒ ํŠธ๋ฆฌ๋ฅผ ๊ตฌ์„ฑํ•˜๊ณ  [0, 5] ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒ ํŠธ๋ฆฌ๋ฅผ ๊ตฌ์„ฑํ•œ๋‹ค.

[3, 2, 1] ๋กœ ๋‹ค์‹œ ๋ฃจํŠธ๋…ธ๋“œ๋Š” ๊ฐ’์ด 3์ด ๋˜๊ณ  ์™ผ์ชฝ ์„œ๋ธŒ ํŠธ๋ฆฌ๋Š” ์—†๊ธฐ ๋•Œ๋ฌธ์— ์ข…๋ฃŒ, [2, 1] ๋กœ ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒ ํŠธ๋ฆฌ๋ฅผ ๊ตฌ์„ฑํ•œ๋‹ค.

๋‚˜๋ˆŒ ์ˆ˜ ์—†์„ ๋•Œ ๊นŒ์ง€ ๊ณ„์† ๋ฐฐ์—ด์„ ๋‚˜๋ˆ„๋ฉฐ ํŠธ๋ฆฌ๋ฅผ ๋งŒ๋“ค๊ธฐ ๋•Œ๋ฌธ์— ์žฌ๊ท€๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.


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 constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
		root = TreeNode(max(nums))

		def make_tree(nums, root):
			left_arr = nums[:nums.index(root.val)]
			right_arr = nums[nums.index(root.val) + 1:]

			if not nums:
				return

			if len(left_arr) >= 1:
				root.left = TreeNode(max(left_arr))
				make_tree(left_arr, root.left)

			if len(right_arr) >= 1:
				root.right = TreeNode(max(right_arr))
				make_tree(right_arr, root.right)

		make_tree(nums, root)
		return root

Categories:

Updated:

Leave a comment