LeetCode 538 Convert BST to Greater Tree
概述
https://leetcode.com/problems/convert-bst-to-greater-tree/
https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/
直接法
先遍历右子树,得到其和,算出当前节点的值,再遍历左子树。
class Solution {
public:
int last = 0;
TreeNode* convertBST(TreeNode* root) {
helper(root);
return root;
}
void helper(TreeNode* root) {
if (!root) return;
helper(root->right);
root->val += last;
last = root->val;
helper(root->left);
}
};