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

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

例如:

输入: 二叉搜索树:
              5
            /   \
           2     13

输出: 转换为累加树:
             18
            /   \
          20     13

解答:

遍历树并使用数组记录各个节点数字,然后再遍历树并通过比对数组中的元素更新节点值

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
     static ArrayList<Integer> arrayList = new ArrayList<>();

    public static void bst(TreeNode root) {
        if (root == null){
            return;
        }
        arrayList.add(root.val);
        bst(root.left);
        bst(root.right);
           }

    public static void bst_(TreeNode root){
        if (root == null){
            return;
        }
        int i = 0;
        int m = root.val;
        for (int num : arrayList){
            if (m < num){
                root.val = root.val + num;
            }
        }
        bst_(root.left);
        bst_(root.right);

    }

    public static TreeNode convertBST(TreeNode root) {
        bst(root);
        Collections.reverse(arrayList);
        bst_(root);
        arrayList.clear();
        return root;
    }
}

后来发现没用审题,题目中说这是BST查询二叉树(节点值有序排列),所以直接遍历右子树就可以知道大于各节点的所有值。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        bst(root);
        return root;
    }
    public void bst(TreeNode root){
        if (root == null) return;
        bst(root.right);
        sum = sum + root.val;
        root.val = sum;
        bst(root.left);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值