-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1305. All Elements in Two Binary Search Trees.cpp
More file actions
72 lines (70 loc) · 2.14 KB
/
Copy path1305. All Elements in Two Binary Search Trees.cpp
File metadata and controls
72 lines (70 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {
/*stack<TreeNode *> s1, s2;
vector<int> result;
while(root1 || root2 || !s1.empty() || !s2.empty()){
while(root1){
s1.push(root1);
root1=root1->left;
}
while(root2){
s2.push(root2);
root2=root2->left;
}
if(s1.empty() || (!s1.empty() && s1.top()->val <= s2.top()->val)){
root1 = s1.top();
s1.pop();
result.push_back(root1->val);
root1 = root1->right;
}else{
root2 = s2.top();
s2.pop();
result.push_back(root2->val);
root2 = root2->right;
}
}
return result;*/
vector<int> res;
stack<TreeNode *> s1, s2;
while (root1 || root2 || !s1.empty() || !s2.empty())
{
while (root1 != NULL)
{
s1.push(root1);
root1 = root1->left;
}
while (root2 != NULL)
{
s2.push(root2);
root2 = root2->left;
}
if (s2.empty() || (!s1.empty() && s1.top()->val <= s2.top()->val))
{
root1 = s1.top();
s1.pop();
res.push_back(root1->val);
root1 = root1->right;
}
else
{
root2 = s2.top();
s2.pop();
res.push_back(root2->val);
root2 = root2->right;
}
}
return res;
}
};