您的位置:首页 > 其它

538. Convert BST to Greater Tree

2017-09-06 22:31 387 查看
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.

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
struct TreeNode* addBST(struct TreeNode* root,int & value) {
if(root == NULL){
return NULL;
}

addBST(root->right,value);
root->val += value;
value = root->val;
addBST(root->left,value);

return root;
}

TreeNode* convertBST(TreeNode* root) {
int value = 0;
if(root == NULL){
return NULL;
}

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