-
Notifications
You must be signed in to change notification settings - Fork 122
/
Copy path1305. All Elements in Two Binary Search Trees.cpp
67 lines (59 loc) · 1.46 KB
/
1305. All Elements in Two Binary Search Trees.cpp
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
// 1305.✅ All Elements in Two Binary Search Trees
class Solution
{
public:
vector<int> v;
vector<int> getAllElements(TreeNode *root1, TreeNode *root2)
{
preorder(root1);
preorder(root2);
sort(v.begin(), v.end());
return v;
}
void preorder(TreeNode *root)
{
if (root == NULL)
return;
v.push_back(root->val);
preorder(root->left);
preorder(root->right);
}
};
// in inorder travesal the elements are in sorted order in a BST
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 (s2.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;
}
};