题目:
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
根节点的值为根节点与右子树的值之和,左子树的结点等于该结点与前面遍历的结点和
具体代码:
/**
* 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
*/
int sum = 0;
TreeNode* convertBST(TreeNode* root) {
// Write your code here
if(root==NULL) return NULL;
else {
convertBST(root->right);
root->val+=sum;
sum=root->val;
convertBST(root->left);
}
return root;
}
};
感悟:
重要的是理清楚递归的思路!