1.题目描述: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.
2.思路:样例
Given a binary search Tree `{5,2,3}`:
5
/ \
2 13
Return the root of new tree
18
/ \
20 13
题目要求为给定一棵二叉查找树把它变成一棵更好的树,也就是新树的新节点值变为原节点值+比它大的节点的值的和。因为它是一颗二叉查找树,所以新根节点=原根节点+原右子树节点,新左子树节点=原左子树节点+原根节点+原右子树节点=原左子树节点+新根节点。应先遍历跟的右子树再遍历根的左子树,并要定义一个变量sum用来储存遍历的值。
3.代码:
/**
* 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
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);
}
}
};
4.感想:这个题目我一开始做的时候一直错误,所有的值都多加了个根节点的值。写遍历函数的时候一定要头脑清晰!