## 题目描述

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``````

## 解法一

### Python

``````# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
origin_root = root
stack = []
current = 0
while root or stack:
if root:
stack.append(root)
root = root.right
else:
node = stack.pop()
current += node.val
node.val = current
root = node.left
return origin_root``````

### Java

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode convertBST(TreeNode root) {
TreeNode originRoot = root;
Stack<TreeNode> stack = new Stack<>();
int current = 0;
while (root != null || !stack.empty()) {
if (root != null) {
stack.push(root);
root = root.right;
} else {
TreeNode node = stack.pop();
current += node.val;
node.val = current;
root = node.left;
}
}
return originRoot;
}
}``````

### C++

``````/**
* 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:
TreeNode *convertBST(TreeNode *root) {
TreeNode *originRoot = root;
stack<TreeNode *> sta;
int current = 0;
while (root != nullptr || !sta.empty()) {
if (root != nullptr) {
sta.push(root);
root = root->right;
} else {
TreeNode *node = sta.top();
sta.pop();
current += node->val;
node->val = current;
root = node->left;
}
}
return originRoot;
}
};``````