[数据结构与算法]leetcode538二叉树转为积累树

给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),
使得每个节点的值是原来的节点值加上所有大于它的节点值之和。 例如:
输入: 原始二叉搜索树:
              5
            /   \
           2     13
输出: 转换为累加树:
             18
            /   \
          20     13
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-bst-to-greater-tree
class Solution {
    List<Integer> list1 = new ArrayList<>();

    public TreeNode convertBST(TreeNode root) {
        if(root == null)  return null;
        midorder(root);
        int cnt = list1.size();
        return midorder(root,cnt);
    }
    public void midorder(TreeNode root){
        if(root.left != null) midorder(root.left);
        list1.add(root.val);
        if(root.right != null) midorder(root.right);
    }

    public TreeNode midorder(TreeNode root,int cnt){
        if(root.left != null) midorder(root.left,cnt);
        int m = 0;
        for(int i=0; i < cnt;i++){
            if(root.val < list1.get(i)){
                m = m + list1.get(i);
            }
        }
        root.val += m;
        if(root.right != null) midorder(root.right,cnt);
        return root;
    }
}

用stack迭代 先算右子树  在左子树
class Solution {
    public TreeNode convertBST(TreeNode root) {
        int sum = 0;
        TreeNode node = root;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        while (!stack.isEmpty() || node != null) {
            /* push all nodes up to (and including) this subtree's maximum on
             * the stack. */
            while (node != null) {
                stack.add(node);
                node = node.right;
            }
            node = stack.pop();
            sum += node.val;
            node.val = sum;
            /* all nodes with values between the current and its parent lie in
             * the left subtree. */
            node = node.left;
        }
        return root;
    }
}
class Solution {

    private int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        traver(root);
        return root;
    }

    private void traver(TreeNode node){
        if(node == null) return ;
        traver(node.right);
        sum += node.val;
        node.val = sum;
        traver(node.left);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值