Published:
Updated:


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