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.
样例
Given a binary search Tree `{5,2,3}`:
5
/ \
2 13
Return the root of new tree
18
/ \
20 13
解题思路:
这道题的关键是搞清楚Greater Tree是怎么由给定的BST树得来的。中心思想依旧是递归,若把和样例中形式一样的树看成最小单元树,则可以进行如下操作:右子树的值不变,根结点的值为根结点与右子树的值之和,左子树的值为左子树与上一步得到的根结点的值之和。因此,此题和普通二叉树的后序遍历相似,需要增加的一点是改变了根结点和左子树的值。
代码实现:
class Solution {
public:
/**
* @param root the root of binary tree
* @return the new root
*/
int rr=0;
TreeNode* convertBST(TreeNode* root) {
// Write your code here
if(root==NULL) return NULL;
else {
convertBST(root->right);
root->val+=rr;
rr=root->val;
convertBST(root->left);
}
return root;
}
};
public:
/**
* @param root the root of binary tree
* @return the new root
*/
int rr=0;
TreeNode* convertBST(TreeNode* root) {
// Write your code here
if(root==NULL) return NULL;
else {
convertBST(root->right);
root->val+=rr;
rr=root->val;
convertBST(root->left);
}
return root;
}
};
A题感悟:
做题之前一定要搞清楚题意,一定要搞清楚新名词的定义。