【LeetCode】每日一题:从二叉搜索树到更大和树——2023.12.4

题目链接从二叉搜索树到更大和树

题干解析:

题目意思很明确,把二叉搜索树中每个节点的val替换为二叉搜索树中所有val大于等于该节点val的节点值之和。

思路分析:

这个题有两种思路:自顶向下自底向上

首先讲一下自顶向下的方法,这个方法理解起来比较简单,但是实现起来比较复杂且臃肿。

对于每一个节点(看作根节点),先计算其左节点(根节点的更大节点和+该节点右子树+本身)和右节点(根节点的根节点的更大节点和+该节点右子树+本身),由此规律进行自顶向下进行递归计算。

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    unordered_map<TreeNode*, int> tree_sum;
    int temp;
    int calculate_tree_sum(TreeNode* root){
        if(root == nullptr){
            return 0;
        }
        if(tree_sum[root]){
            return tree_sum[root];
        }
        tree_sum[root] = root -> val + calculate_tree_sum(root -> left) + calculate_tree_sum(root -> right);
        return tree_sum[root];

    }
    void swap(TreeNode* root, int bigger){
        if(root == nullptr){
            return;
        }
        int temp = root -> val;
        root -> val += calculate_tree_sum(root -> right) + bigger;
        swap(root -> left, root -> val);
        swap(root -> right, bigger);
    }

    TreeNode* bstToGst(TreeNode* root) {
        swap(root, 0);
        return root;
    }
};

另外一种是自底向上的解法:

这个方法利用到二叉树的性质,先迭代至二叉搜索树右端底部,随后往回迭代。优雅~

class Solution {
public:
    int sum = 0;

    TreeNode* bstToGst(TreeNode* root) {
        if (root != nullptr) {
            bstToGst(root->right);
            sum += root->val;
            root->val = sum;
            bstToGst(root->left);
        }
        return root;
    }
};

作者:力扣官方题解
链接:https://leetcode.cn/problems/binary-search-tree-to-greater-sum-tree/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值