[LeetCode] 1038. Binary Search Tree to Greater Sum Tree

Updated:

1038. Binary Search Tree to Greater Sum Tree

์ด์ง„ ํƒ์ƒ‰ ํŠธ๋ฆฌ๋ฅผ ํ†ตํ•ด ์ตœ๋Œ€๊ฐ’์„ ๊ฐ€์ง„ ๋…ธ๋“œ๋ถ€ํ„ฐ ์ฐจ๋ก€๋Œ€๋กœ ํƒ์ƒ‰ ํ•ด ๊ณ„์† ๊ฐ’์„ ๋”ํ•ด ๋…ธ๋“œ์— ๋‹ค์‹œ ์ €์žฅํ•ด์ฃผ๋Š” ๋ฌธ์ œ.

[Python] Binary Search Tree ์ด ๊ธ€์„ ๋ณด๋ฉด ์ด์ง„ ํƒ์ƒ‰ ํŠธ๋ฆฌ๊ฐ€ ์ฃผ์–ด์ง„ ๊ฒฝ์šฐ ์ค‘์œ„์ˆœํšŒ๋ฅผ ํ•˜๋ฉด ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ ๋œ ๊ฐ’์„ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค.

์ค‘์œ„์ˆœํšŒ๋Š” ์™ผ์ชฝ ๋ถ€ํŠธ๋ฆฌ โ†’ย ๋ฃจํŠธ โ†’ย ์˜ค๋ฅธ์ชฝ ๋ถ€ํŠธ๋ฆฌ ์ˆœ์„œ๋กœ ํƒ์ƒ‰์„ ํ•œ๋‹ค.

ํ•˜์ง€๋งŒ ์ด ๊ฒฝ์šฐ์—๋Š” ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ ๋œ ๊ฐ’์„ ๊ตฌํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์˜ค๋ฅธ์ชฝ ๋ถ€ํŠธ๋ฆฌ โ†’ ๋ฃจํŠธ โ†’ ์™ผ์ชฝ ๋ถ€ํŠธ๋ฆฌ ์ˆœ์„œ๋กœ ๋ฐ”๊ฟ”์ค€๋‹ค.

๋…ธ๋“œ ๊ฐ’์˜ ํ•ฉ ๊ฐ™์€ ๊ฒฝ์šฐ๋Š” ์ „์—ญ๋ณ€์ˆ˜๋กœ ๋งŒ๋“ค์–ด ๊ด€๋ฆฌํ•˜๊ธฐ ์‰ฝ๊ฒŒ ํ•˜์˜€๋‹ค.


from typing import List


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


class Solution:
	def bstToGst(self, root: TreeNode) -> TreeNode:
		global _sum
		_sum = 0

		def post_order(cur_node):
			global _sum
			if not cur_node:
				return
			else:
				post_order(cur_node.right)
				_sum += cur_node.val
				cur_node.val = _sum
				post_order(cur_node.left)

		post_order(root)
		return root

Categories:

Updated:

Leave a comment