The trick here is to name the state correctly, then let the implementation follow. For 1448. Count Good Nodes in Binary Tree, the solution in this repository is mainly a two pointers solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. 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 dfs, goodNodes.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- 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: 244 ms, faster than 33.33% of C++ online submissions for Count Good Nodes in Binary Tree.
02//Memory Usage: 86.4 MB, less than 100.00% of C++ online submissions for Count Good Nodes in Binary Tree.
03/**
04 * Definition for a binary tree node.
05 * struct TreeNode {
06 * int val;
07 * TreeNode *left;
08 * TreeNode *right;
09 * TreeNode() : val(0), left(nullptr), right(nullptr) {}
10 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
11 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
12 * };
13 */
14class Solution {
15public:
16 int ans;
17
18 void dfs(TreeNode* node, int upper){
19 if(node == nullptr) return;
20 if(node->val >= upper){
21 ans++;
22 }
23 dfs(node->left, max(node->val, upper));
24 dfs(node->right, max(node->val, upper));
25 };
26
27 int goodNodes(TreeNode* root) {
28 ans = 0;
29 dfs(root, root->val);
30 return ans;
31 }
32};
Cost