题目: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.
思路:中序遍历(右子树—跟节点—左子树)。
代码:
class Solution {
public:
/**
* @param root the root of binary tree
* @return the new root
*/
int sum=0;
TreeNode* convertBST(TreeNode* root) {
// Write your code here
if(root==NULL) return NULL;
travel(root);
return root;
}
void travel(TreeNode* root)
{
if(root==NULL) return;
if(root->right!=NULL)
travel(root->right);
sum+=(root->val);
root->val=sum;
if(root->left!=NULL)
travel(root->left);
}
};
感想:这道题很难,我原本想分好几类情况讨论下来,但是完全行不通。这是从网上搜的答案。