A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 1038. Binary Search Tree to Greater Sum Tree, the solution in this repository is mainly a two pointers solution.
Guide
What?
The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: two pointers.
Guide
When?
This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are inOrder, bstToGst.
Guide
Why?
The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 4 ms, faster than 63.25% of C++ online submissions for Binary Search Tree to Greater Sum Tree.
02//Memory Usage: 9.1 MB, less than 100.00% of C++ online submissions for Binary Search Tree to Greater Sum Tree.
03
04/**
05 * Definition for a binary tree node.
06 * struct TreeNode {
07 * int val;
08 * TreeNode *left;
09 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13class Solution {
14public:
15 int acc = 0;
16 void inOrder(TreeNode* node){
17 //in-order traversal, from right to left
18
19 //visit right child
20 if(node->right) inOrder(node->right);
21
22 //visit itself
23 node->val += acc;
24 //acc becomes old node->val + acc
25 acc = node->val;
26
27 //visit left child
28 if(node->left) inOrder(node->left);
29 };
30
31 TreeNode* bstToGst(TreeNode* root) {
32 if(root) inOrder(root);
33 return root;
34 }
35};
Cost