538. Convert binary search tree to cumulative tree
Using class variables in Java is equivalent to using global variables in C++.
It is the first time to use the knowledge of global variables in Java.
/**
* 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 sum = 0; //设置成员变量sum,每次都累积,这样就可以在遍历左子树的时候累积右边的了。
public TreeNode convertBST(TreeNode root) {
// 先更新右孩子,再更新左孩子
if(root == null) return root;
convertBST(root.right);
sum += root.val;
root.val = sum;
convertBST(root.left);
return root;
}
}