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
思路
- 题目大意:给定一棵二叉搜索树,将它转化为更大的二叉树,规则是:结点的值 = 该结点的值 + 所有比它大的结点的值的和。
- 转化后,二叉树变成左边大,右边小,刚好和二叉搜索树相反
- 步骤
- 对二叉搜索树中序遍历,设置一个数组,保存中序遍历的值,得到从小到大排序的nums
- 对二叉搜索树再次进行中序遍历,将遍历结点的值 加上所有大于它的值。
- 注意
- 得到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;
}