1.描述
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.
样例
Given a binary search Tree `{5,2,3}`:
5
/ \
2 13
Return the root of new tree
18
/ \
20 13
2.分析
给定二进制搜索树(BST),将其转换为更大的树,使原始BST的每个键都更改为原始密钥
加上大于BST中原始密钥的所有键的总和。即把所有大于本身节点值的加到当前节点上。
3.代码
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root the root of binary tree
* @return the new root
*/
void changeval(TreeNode* root, int& sum){
if(root==NULL) return;
changeval(root->right, sum);//首先把所有右孩子的值加到节点上
root->val =root->val+sum;
changeval(root->left, root->val);//把子树中左孩子的值也加到节点上
}
TreeNode* convertBST(TreeNode* root) {
// Write your code here
int sum = 0;
changeval(root, sum);
return root;
}
};
4.总结
这里注意并不是单纯的把当前节点的右子树所以节点值加起来,若当前节点为双亲节点的左子树,
双亲节点的值也要加上。