​LeetCode刷题实战538:把二叉搜索树转换为累加树

本文介绍了如何解决LeetCode上的一个问题——将二叉搜索树转换为累加树。文章通过中序遍历的方法,讲解了如何利用递归改变每个节点的值,使其等于原树中大于或等于该节点值的所有节点之和。通过这样的转换,每个节点的值都会增加,从而实现累加树的构建。文章以Java代码为例,展示了具体的实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 把二叉搜索树转换为累加树,我们先来看题面:

https://leetcode-cn.com/problems/convert-bst-to-greater-tree/

Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.

As a reminder, a binary search tree is a tree that satisfies these constraints:

1.The left subtree of a node contains only nodes with keys less than the node's key.

2.The right subtree of a node contains only nodes with keys greater than the node's key.

3.Both the left and right subtrees must also be binary search trees.

给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。

提醒一下,二叉搜索树满足下列约束条件:

  • 节点的左子树仅包含键 小于 节点键的节点。

  • 节点的右子树仅包含键 大于 节点键的节点。

  • 左右子树也必须是二叉搜索树。


示例                         

fbe8a952fc702f26666ffa816703053c.png


解题

思路:多写两层搜索树就会很明显的发现,所求的每个节点的值就是该节点的右子树所有节点的和加上自身的节点值,所以采用中序遍历,从右子树开始遍历即可,设置一个全局变量sum用于记录节点值的和。

e9b1d496ca74c277c2e8f0e5e871ddae.png

/**
 * 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;
    public TreeNode convertBST(TreeNode root) {
        if(root != null){
            convertBST(root.right);
            sum += root.val;
            root.val = sum;
            convertBST(root.left);
 
        }
        return root;
    }
}

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-520题汇总,希望对你有点帮助!

LeetCode刷题实战521:最长特殊序列 Ⅰ

LeetCode刷题实战522:最长特殊序列 II

LeetCode刷题实战523:连续的子数组和

LeetCode刷题实战524:通过删除字母匹配到字典里最长单词

LeetCode刷题实战525:连续数组

LeetCode刷题实战526:优美的排列

LeetCode刷题实战527:单词缩写

LeetCode刷题实战528:按权重随机选择

LeetCode刷题实战529:扫雷游戏

LeetCode刷题实战530:二叉搜索树的最小绝对差

LeetCode刷题实战531:孤独像素 I

LeetCode刷题实战532:数组中的K-diff数对

LeetCode刷题实战533:孤独像素 II

LeetCode刷题实战534:游戏玩法分析 III

LeetCode刷题实战535:TinyURL 的加密与解密

LeetCode刷题实战536:从字符串生成二叉树

LeetCode刷题实战537:复数乘法

c7aaacd41a0041d90f8af6179a0368bf.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程IT圈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值