538. Convert BST to Greater Tree 二叉搜索树转化为更大的树

538. Convert BST to Greater Tree

问题描述

Given 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 sum of all keys greater than the original key in BST.

Example:

Input: The root of a Binary Search Tree like this:
5
/ \
2 13

Output: The root of a Greater Tree like this:
18
/ \
20 13

思路
  • 题目大意:给定一棵二叉搜索树,将它转化为更大的二叉树,规则是:结点的值 = 该结点的值 + 所有比它大的结点的值的和。
  • 转化后,二叉树变成左边大,右边小,刚好和二叉搜索树相反
  • 步骤
    1. 对二叉搜索树中序遍历,设置一个数组,保存中序遍历的值,得到从小到大排序的nums
    2. 对二叉搜索树再次进行中序遍历,将遍历结点的值 加上所有大于它的值。
  • 注意
    • 得到nums数组后,将其反转,得到降序排序的数组nums,然后每次求和后只需将nums的最后一个值pop出去
代码
//538. Convert BST to Greater Tree
TreeNode* convertBST(TreeNode* root) {
    vector<int> nums = getMidorderNums(root);
    reverse(nums.begin(), nums.end());
    TreeNode* t = root;
    stack<TreeNode*> s;
    if (!t)
    {
        printf("the tree is empty\n");
    }
    else
    {
        while (t || !s.empty())
        {
            while (t)
            {
                s.push(t);
                t = t->left;
            }
            t = s.top();
            s.pop();
            for (int i = 0; i<nums.size() -1; i++)
            {
                t->val += nums[i];
            }
            nums.pop_back();
            t = t->right;
        }
    }
    return root;
}
// 保存中序遍历的值
vector<int> getMidorderNums(TreeNode* root)
{
    vector<int> nums;
    if (root == nullptr)
        return nums;
    vector<int> nums_l = getMidorderNums(root->left);
    nums = nums_l;
    nums.push_back(root->val);
    vector<int> nums_r = getMidorderNums(root->right);
    nums.insert(nums.end(), nums_r.begin(), nums_r.end());
    return nums;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值