-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC1305.cpp
More file actions
executable file
·40 lines (37 loc) · 852 Bytes
/
LC1305.cpp
File metadata and controls
executable file
·40 lines (37 loc) · 852 Bytes
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
/*
Problem Statement: https://leetcode.com/problems/all-elements-in-two-binary-search-trees/
Time: O(n)
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {
vector<int> b1, b2, b3;
inorder(root1, b1);
inorder(root2, b2);
merge(b1, b2, b3);
return b3;
}
void inorder(TreeNode* node, vector<int>& b) {
if (!node)
return;
inorder(node->left, b);
b.push_back(node->val);
inorder(node->right, b);
}
void merge(vector<int>& b1, vector<int>& b2, vector<int>& b3) {
int i, j;
i = j = 0;
while (i < b1.size() && j < b2.size()) {
if (b1[i] < b2[j])
b3.push_back(b1[i++]);
else
b3.push_back(b2[j++]);
}
while (i < b1.size())
b3.push_back(b1[i++]);
while (j < b2.size())
b3.push_back(b2[j++]);
}
};