一:题目
二:上码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
/**
思路:
1:确定递归函数的参数跟返回值
2.确定终止条件
当遍历为空的时候 我们需要 return
*/
public void order(TreeNode root,List<Integer> list) {
if (root == null) return ;
order(root.left,list);
list.add(root.val);
order(root.right,list);
}
public int getSum(List<Integer> list,int nums) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
if (list.get(i) >= nums) sum += list.get(i);
}
return sum;
}
public void getAns(TreeNode root,List<Integer>list) {
if (root == null) return ;
int sum = getSum(list,root.val);
root.val = sum;
getAns(root.left,list);
getAns(root.right,list);
}
public TreeNode convertBST(TreeNode root) {
List<Integer>list = new ArrayList<>();
order(root,list);
getAns(root,list);
return root;
}
}