/
1305. All Elements in Two Binary Search Trees 2.cpp
77 lines (65 loc) · 1.8 KB
/
1305. All Elements in Two Binary Search Trees 2.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
68
69
70
71
72
73
74
75
76
77
// https://leetcode.com/problems/all-elements-in-two-binary-search-trees/
/**
* 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)
{
vector<int> nodes;
insertNodes(root1, nodes);
insertNodes(root2, nodes);
quickSort(nodes, 0, nodes.size() - 1);
return nodes;
}
void insertNodes(TreeNode *root, vector<int> &nodes)
{
if (root == nullptr)
return;
nodes.push_back(root->val);
insertNodes(root->left, nodes);
insertNodes(root->right, nodes);
}
int partition(vector<int> &nodes, int left, int right)
{
int i = left;
int j = right;
int pivotIndex = left + (right - left) / 2;
int pivotValue = nodes[pivotIndex];
int temp;
while (i <= j)
{
while (nodes[i] < pivotValue)
i++;
while (nodes[j] > pivotValue)
j--;
if (i <= j)
{
temp = nodes[i];
nodes[i] = nodes[j];
nodes[j] = temp;
i++;
j--;
}
}
return i;
}
void quickSort(vector<int> &nodes, int left, int right)
{
if (left < right)
{
int pivotIndex = partition(nodes, left, right);
quickSort(nodes, left, pivotIndex - 1);
quickSort(nodes, pivotIndex, right);
}
}
};