力扣算法:把二叉搜索树转换为累加树

原题链接:https://leetcode-cn.com/problems/convert-bst-to-greater-tree

给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。

思路:因为给定的树为 二叉搜索树,即中序遍历是从小到大排列的。这道题可以采用反向中序遍历,定一个值为反向中序遍历的和,每遍历一个就加上一个。

具体代码如下:

public TreeNode convertBST(TreeNode root) {
        List<Integer> result = new ArrayList<>();  //为了记录和,不能使用int  ,因为不是对象类型的,会丢失数据
        result.add(0);   //初始和为0
        TreeNode t=root;
        getNum(result, t);
        return root;
    }
    public void getNum(List<Integer> result,TreeNode root){
        if(root==null)
            return;
        getNum(result,root.right);
        int sum=result.get(0);
        result.remove(0);
        result.add(sum+root.val);
        root.val=sum+root.val;
        getNum(result,root.left);
    }
原文地址:https://www.cnblogs.com/wys-373/p/13707292.html