从二叉搜索树到更大和树 (Binary Search Tree to Greater Sum Tree)

 

思路:

// @Title: 从二叉搜索树到更大和树 (Binary Search Tree to Greater Sum Tree)
// @Author: qisiii
// @Date: 2024-09-16 18:48:58
// @Runtime: 0 ms
// @Memory: 40.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 bstToGst(TreeNode root) {
        if(root==null){
            return null;
        }
        bstToGst(root.right);
        root.val+=prev;
        prev=root.val;
        bstToGst(root.left);
        return root;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18