★538. 把二叉搜索树转换为累加树

538. 把二叉搜索树转换为累加树

在Java中使用类变量,就相当于用了C++ 中的全局变量。
第一次在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;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45895217/article/details/134828308