問題描述:
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
在解題時要注意先遍歷右子樹,並且要進行後序遍歷,注意改變sum的值
代碼:
/**
* 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 SUM(TreeNode* root,int&sum)
{if(root==NULL) return ;
else{
SUM(root->right,sum);
root->val+=sum;
sum=root->val;
SUM(root->left,sum);
}
}
TreeNode* convertBST(TreeNode* root) {
int sum;
SUM(root,sum);
return root;
// Write your code here
}
};
感悟:
在寫代碼前要考慮全面,開始沒有考慮到後續遍歷。