Let's make this one less mysterious. For 1123. Lowest Common Ancestor of Deepest Leaves, the solution in this repository is mainly a two pointers solution.
Guide
What?
Before optimizing anything, pin down what information is still useful after each move. 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, sliding window.
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 lcaDeepestLeaves.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
- The queue gives the solution a level-by-level or frontier-style traversal.
- 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:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
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: 16 ms, faster than 80.00% of C++ online submissions for Lowest Common Ancestor of Deepest Leaves.
02//Memory Usage: 21.6 MB, less than 100.00% of C++ online submissions for Lowest Common Ancestor of Deepest Leaves.
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 TreeNode* lcaDeepestLeaves(TreeNode* root) {
16 //find deepest leaves, and then return their LCA
17 map<TreeNode*, TreeNode*> parent; //depth and parent
18 int level, level_count, next_level_count;
19 vector<TreeNode*> level_nodes;
20 queue<TreeNode*> q;
21 TreeNode* cur;
22
23 //find deepest leaves
24 q.push(root);
25 level = 0; level_count = 1; next_level_count = 0;
26
27 while(!q.empty()){
28 cur = q.front(); q.pop();
29 level_nodes.push_back(cur);
30
31 if(cur->left){
32 q.push(cur->left);
33 parent[cur->left] = cur;
34 next_level_count++;
35 }
36
37 if(cur->right){
38 q.push(cur->right);
39 parent[cur->right] = cur;
40 next_level_count++;
41 }
42
43 level_count--;
44 if(level_count == 0){
45 level_count = next_level_count;
46 next_level_count = 0;
47 if(!q.empty()){
48 level++;
49 level_nodes.clear();
50 }
51 }
52 }
53 //level_nodes is now deepest leaves
54
55 //find LCA
56 //only one leaf
57 // cout << level_nodes.size() << endl;
58 if(level_nodes.size() == 1) return level_nodes[0];
59
60 //more than one leaf
61 TreeNode* first_parent;
62
63 while(true){
64 first_parent = parent[level_nodes[0]];
65 bool same_parent = true;
66 for(int i = 1; i < level_nodes.size(); i++){
67 if(parent[level_nodes[i]] != first_parent){
68 same_parent = false;
69 break;
70 }
71 }
72 if(same_parent) break;
73 //if parent not common, use grandparent
74 //this is valid because all "level_nodes" are at the same level!
75 for(int i = 0; i < level_nodes.size(); i++){
76 parent[level_nodes[i]] = parent[parent[level_nodes[i]]];
77 }
78 }
79
80 return first_parent;
81 }
82};
Cost