สมมติว่าเรามีต้นไม้ค้นหาทวิภาค (BST) สองต้น เราต้องคืนค่ารายการค่าที่มีองค์ประกอบทั้งหมดที่ปรากฏในต้นไม้ทั้งสอง และรายการต้องเรียงจากน้อยไปมาก
ตัวอย่าง ต้นไม้สองต้นดังภาพ:

ผลลัพธ์: [0,1,1,2,3,4]
ขั้นตอนการแก้ปัญหา (In-order Traversal แบบ Iterative)
- กำหนดอาร์เรย์
ans, สองสแต็กst1และst2 curr1 := root1,curr2 := root2- ใส่โหนด
root1และโหนดซ้ายทั้งหมดเข้าst1, ใส่root2และโหนดซ้ายทั้งหมดเข้าst2 whilest1ไม่ว่าง หรือst2ไม่ว่าง:- ถ้า
st1ไม่ว่าง และ (st2ว่าง หรือค่าของโหนดบนสุดst1 <= st2):temp := top ของ st1, ลบออกจากst1- ใส่ค่า
tempเข้าans - ใส่โหนดขวาของ
tempและโหนดซ้ายทั้งหมดของมันเข้าst1
- อื่นๆ:
temp := top ของ st2, ลบออกจากst2- ใส่ค่า
tempเข้าans - ใส่โหนดขวาของ
tempและโหนดซ้ายทั้งหมดของมันเข้าst2
- ถ้า
- คืนค่า
ans
ตัวอย่างโค้ด (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 = NULL;
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;
TreeNode* curr1 = root1;
TreeNode* curr2 = root2;
pushLeft(st1, curr1);
pushLeft(st2, curr2);
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));
}
อินพุต
[2,1,4] [1,0,3]
เอาต์พุต
[0,1,1,2,3,4]