您的位置:首页 > 其它

538. Convert BST to Greater Tree

2017-06-18 12:46 471 查看
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.

Example:

Input: The root of a Binary Search Tree like this:
5
/   \
2     13

Output: The root of a Greater Tree like this:
18
/   \
20     13


Subscribe to see which companies asked this question.

将搜索二叉树按节点的值从大到小累加。累加过程中,累加的值存在节点中。这种按顺序的操作联想到了中序遍历,可以看做是从后向前的中序遍历。

代码:

class Solution
{
public:
TreeNode* convertBST(TreeNode* root)
{
inorder(root);
return root;
}
private:
void inorder(TreeNode* root)
{
if(root)
{
inorder(root->right);
root->val += sum;
sum = root->val;
inorder(root->left);
}
}

int sum = 0;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  bst