问题描述:
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。
实现思路:
利用递归,左子树加上它本身和根节点和右子树的值,根节点再加上右子树的值,右子树不变。
实现代码:
/**
* 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:
std::vector<int> v;
/**
* @param root the root of binary tree
* @return the new root
*/
TreeNode* convertBST(TreeNode* root) {
// Write your code here
int sum=0;
convert(root,sum);
return root;
}
void convert(TreeNode *root,int &sum)
{
if(root!=NULL)
{convert(root->right,sum);
root->val+=sum;
sum=root->val;
convert(root->left,sum);
}
}
};
感想:
利用递归,和二叉排序树的性质