Solution
# 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:
val = 0
def bstToGst(self, root: TreeNode) -> TreeNode:
if root:
self.bstToGst(root.right)
# self.val: μ§κΈκΉμ§ λμ λ κ°
# root.val: νμ¬ λ
Έλμ κ°
# μ¦, inorder λ°©μμΌλ‘ νμ¬ λ
Έλμ κ°μ μκΈ° μμ μ ν¬ν¨ν μ§κΈκΉμ§μ λμ λ κ°κ³Ό ν©μΉ¨
# self.valμ νμ¬ λ
Έλμ κ° root.valμ λν¨ -> νμ¬ λ
Έλμ κ°μ μ΄μ μ λ°©λ¬Έν λ
Έλλ€μ ν©κ³Ό λνλ κ²μ μλ―Έ
# root.valμ self.valλ‘ μ
λ°μ΄νΈνμ¬ νμ¬ λ
Έλμ κ°μ λμ λ κ°μΌλ‘ λ³κ²½
self.val += root.val
root.val = self.val
self.bstToGst(root.left)
return root
Leave a comment