538. 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.
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
将一棵二叉搜索树变成一棵更大的二叉搜索树
C++(40ms):
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) 8 * }; 9 */ 10 class Solution { 11 private: 12 int sum = 0 ; 13 public: 14 void travel(TreeNode* root){ 15 if (!root) 16 return ; 17 if (root->right) 18 travel(root->right) ; 19 sum += root->val ; 20 root->val = sum ; 21 if (root->left) 22 travel(root->left) ; 23 } 24 25 TreeNode* convertBST(TreeNode* root) { 26 travel(root) ; 27 return root ; 28 } 29 };