This is one of those problems where the clean idea matters more than the amount of code. For 1305. All Elements in Two Binary Search Trees, 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, stack, sliding window, greedy.
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 dfs, getAllElements.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
- The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
- 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//Runtime: 280 ms, faster than 58.55% of C++ online submissions for All Elements in Two Binary Search Trees.
02//Memory Usage: 58.1 MB, less than 100.00% of C++ online submissions for All Elements in Two Binary Search Trees.
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 vector<int> ans;
16
17 void dfs(TreeNode* root){
18 stack<TreeNode*> stk;
19 TreeNode *node;
20
21 stk.push(root);
22 while(!stk.empty()){
23 node = stk.top(); stk.pop();
24 if(!node) return;
25 ans.push_back(node->val);
26 if(node->left){
27 stk.push(node->left);
28 }
29 if(node->right){
30 stk.push(node->right);
31 }
32 }
33 }
34
35 vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {
36 dfs(root1);
37 dfs(root2);
38 sort(ans.begin(), ans.end());
39 return ans;
40 }
41};
Cost