題目描述:https://leetcode.com/problems/convert-bst-to-greater-tree/#/description
解題思路:後續遍歷,每個節點的值等於其自身值加上其已經遍歷過的值之和。
AC代碼
public class Solution {
int count = 0;
public TreeNode convertBST(TreeNode root) {
if(root == null) return null;
convert(root);
return root;
}
public void convert(TreeNode root){
if(root == null) return;
convert(root.right);
count += root.val;
root.val = count;
convert(root.left);
}
}