题目:
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
思路:
首先计算出整个树中的所有结点的值的和sum,然后采用中序遍历(因为这种遍历是有序的)。对于遍历到的这个结点,首先从sum中减去这个结点的值,然后更新该结点的值为当前值加上sum的当前值。
原来觉得应该用数组存储中序遍历下结点的累积和,后来发现不需要,只需要一个sum就可以了。算法的时间复杂度是O(n),空间复杂度是O(1),其中n是树中的结点个数。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
int sum = getSum(root);
inOrder(root, sum);
return root;
}
private:
int getSum(TreeNode *root) {
if (root == NULL) {
return 0;
}
int left_sum = getSum(root->left);
int right_sum = getSum(root->right);
return left_sum + root->val + right_sum;
}
void inOrder(TreeNode *root, int &sum) {
if (root == NULL) {
return;
}
inOrder(root->left, sum);
sum -= root->val;
root->val += sum;
inOrder(root->right, sum);
}
};