原题链接:https://leetcode.com/problems/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 13Output: The root of a Greater Tree like this:
18
/ \
20 13
题目的大致含义就是要将一颗二叉搜索树进行操作,将里面节点值换成它本身的值再加上树里所有大于它的节点的值,这道题刚一看上去真不知从何下手,但做这道题之前,要先对二叉搜索树有一个大致的了解,即它同时也是一个排序二叉树,左边子节点的值小于父节点的值,右边子节点的值大于父节点的值。
知道这一特性以后,我们就可以利用这一特点,可以先对右边较大值的节点先进行处理,然后再父节点,再左节点,这样的话我们就会联想起中序遍历也有相同的特点,只是我们解这道题需要反着进行中序遍历,问题即可迎刃而解。
提供以下参考代码(已AC):
class Solution {
private:
int num = 0;
public:
void traverse(TreeNode* root) {
if (root != NULL) {
if (root->right) traverse(root->right);
num += root->val;
root->val = num;
if (root->left) traverse(root->left);
}
}
TreeNode* convertBST(TreeNode* root) {
traverse(root);
return root;
}
};