Cho hai cây tìm kiếm nhị phân (BST), trả về danh sách tất cả giá trị có trong cả hai cây theo thứ tự tăng dần.
Ví dụ với hai cây:

Kết quả: [0,1,1,2,3,4].
Giải thuật (Duyệt inorder song song)
- Khởi tạo mảng
ans, hai ngăn xếpst1,st2. curr1 = root1,curr2 = root2.- Đẩy
root1và tất cả nút con trái vàost1, tương tự choroot2vàost2. - Khi
st1hoặcst2không rỗng: - Nếu
st1không rỗng và (st2rỗng hoặc đỉnhst1≤ đỉnhst2): - Lấy
temp= đỉnhst1, pop. - Thêm giá trị
tempvàoans. - Đẩy nút phải của
tempvà tất cả con trái vàost1. - Ngược lại, làm tương tự với
st2. - Trả về
ans.
Ví dụ C++
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v) {
cout << "[";
for(int i = 0; i < v.size(); i++) cout << v[i] << ", ";
cout << "]" << endl;
}
class TreeNode {
public:
int val;
TreeNode *left, *right;
TreeNode(int data) { val = data; left = right = NULL; }
};
void insert(TreeNode **root, int val) {
queue<TreeNode*> q; q.push(*root);
while(q.size()) {
TreeNode *temp = q.front(); q.pop();
if(!temp->left) {
if(val != NULL) temp->left = new TreeNode(val);
else temp->left = new TreeNode(0);
return;
} else q.push(temp->left);
if(!temp->right) {
if(val != NULL) temp->right = new TreeNode(val);
else temp->right = new TreeNode(0);
return;
} else q.push(temp->right);
}
}
TreeNode *make_tree(vector<int> v) {
TreeNode *root = new TreeNode(v[0]);
for(int i = 1; i < v.size(); i++) insert(&root, v[i]);
return root;
}
class Solution {
public:
void pushLeft(stack<TreeNode*>& st, TreeNode* root) {
TreeNode* curr = root;
while(curr) { st.push(curr); curr = curr->left; }
}
vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {
vector<int> ans;
stack<TreeNode*> st1, st2;
pushLeft(st1, root1);
pushLeft(st2, root2);
while(!st1.empty() || !st2.empty()) {
TreeNode* temp;
if(!st1.empty() && (st2.empty() || st1.top()->val <= st2.top()->val)) {
temp = st1.top(); st1.pop();
ans.push_back(temp->val);
pushLeft(st1, temp->right);
} else {
temp = st2.top(); st2.pop();
ans.push_back(temp->val);
pushLeft(st2, temp->right);
}
}
return ans;
}
};
int main() {
vector<int> v = {2,1,4};
TreeNode *root1 = make_tree(v);
v = {1,0,3};
TreeNode *root2 = make_tree(v);
Solution ob;
print_vector(ob.getAllElements(root1, root2));
return 0;
}
Đầu vào
[2,1,4] [1,0,3]
Đầu ra
[0,1,1,2,3,4]