思路:
// @Title: 把二叉搜索树转换为累加树 (Convert BST to Greater Tree)
// @Author: qisiii
// @Date: 2024-09-16 18:47:22
// @Runtime: 0 ms
// @Memory: 44.2 MB
// @comment:
// @flag:
/**
* 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 {
int prev=0;
public TreeNode convertBST(TreeNode root) {
if(root==null){
return null;
}
convertBST(root.right);
root.val+=prev;
prev=root.val;
convertBST(root.left);
return root;
}
}