This is one of those problems where the clean idea matters more than the amount of code. For 1026. Maximum Difference Between Node and Ancestor, the solution in this repository is mainly a two pointers solution.
Guide
What?
The code is easier to read if we treat it as a controlled search through possible states. 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.
The notes already sitting in the source point us in the right direction:
- https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/274610/JavaC%2B%2BPython-Top-Down
- Top Down
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are maxAncestorDiffMM, maxAncestorDiff.
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:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
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//https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/274610/JavaC%2B%2BPython-Top-Down
02
03//Top Down
04//Runtime: 4 ms, faster than 96.94% of C++ online submissions for Maximum Difference Between Node and Ancestor.
05//Memory Usage: 11.9 MB, less than 86.36% of C++ online submissions for Maximum Difference Between Node and Ancestor.
06
07/**
08 * Definition for a binary tree node.
09 * struct TreeNode {
10 * int val;
11 * TreeNode *left;
12 * TreeNode *right;
13 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
14 * };
15 */
16class Solution {
17public:
18 int maxAncestorDiffMM(TreeNode* node, int mx, int mn){
19 return node ? max(maxAncestorDiffMM(node->left, max(node->val, mx), min(node->val, mn)),
20 maxAncestorDiffMM(node->right, max(node->val, mx), min(node->val, mn))): mx-mn;
21 }
22
23 int maxAncestorDiff(TreeNode* root) {
24 return maxAncestorDiffMM(root, 0, INT_MAX);
25 }
26};
Cost