538. Convert binary search tree to cumulative tree
Problem-solving ideas
Transforming the in-order traversal algorithm
Because the results of in-order traversal are all sorted in ascending order, then if the right subtree is traversed first and then the left subtree is traversed, the result will be in descending order.
Finally, we set a variable to accumulate all the intermediate values, and the result is the value of all nodes larger than the current node.
/**
* 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;
* }
* }
*/classSolution{
int sum =0;publicTreeNodeconvertBST(TreeNode root){
// 改造中序遍历算法traverse(root);return root;}voidtraverse(TreeNode root){
if(root ==null){
return;}traverse(root.right);
sum += root.val;// 每次叠加最大值 比他大的所有节点// 将BST 转化为累加树
root.val = sum;traverse(root.left);}}