์ฝ๋
class Solution {
int sum = 0;
public TreeNode bstToGst(TreeNode root) {
if (root != null) {
// ์ค๋ฅธ์ชฝ ๋
ธ๋๋ถํฐ ๋ฐ๋๋ก ํ์
bstToGst(root.right);
// ํ์ฌ ๋
ธ๋ ๊ฐ ์ถ๊ฐ -> ํ์ฌ ๋
ธ๋๋ณด๋ค ํฐ ๊ฐ์ ํฉ๊ณ๊ฐ ๋จ.
sum += root.val;
root.val = sum;
// ์ผ์ชฝ ๋
ธ๋ ํ์ -> ์ด๋ฏธ ๋ ํฐ ๊ฐ๋ค์ ๋ชจ๋ ์ฒ๋ฆฌํ์ผ๋ฏ๋ก ์ผ์ชฝ์์ ์ฌ๊ท๋๋ฆฌ๋ฉด ๋๊ฐ์ด ์ํ ๊ฐ๋ฅ.
bstToGst(root.left);
}
return root;
}
}
Java
๋ณต์ฌ