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 13Output: The root of a Greater Tree like this:
18
/ \
20 13
题目内容:
题目给出一个二叉搜索树,让我们将它转换成greater tree,greet tree的节点的值就是对应二叉搜索树中改点的值加上所有比它大的节点的值的和。
解题思路:
因为二叉搜索树中,左节点及其子节点都比根节点小,右节点及其子节点都比根节点大,所以应该要先一直访问右节点,找到最大的节点,然后开始回溯,每回溯到一个点,则开始访问这个点的右节点(如果没访问过的话),然后再访问右节点,且在回溯的时候,每访问到一个点,就把这些点的值累加起来,就一直这样进行递归回溯的操作,知道访问完所有的节点,就可以将一个二叉搜索树转换成greater tree。
代码:
class Solution {
public:
int current_sum;
TreeNode* convertBST(TreeNode* root) {
current_sum = 0;
sum(root);
return root;
}
void sum(TreeNode* root) {
if (root == NULL) return;
sum(root->right);
current_sum += root->val;
root->val = current_sum;
sum(root->left);
}
};