-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPOTD-Find Common Nodes in two BSTs.cpp
48 lines (46 loc) · 1.37 KB
/
POTD-Find Common Nodes in two BSTs.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
class Solution
{
public:
//Function to find the nodes that are common in both BST.
vector <int> findCommon(Node *root1, Node *root2)
{
vector<int> result;
stack<Node*> stack1;
stack<Node*> stack2;
while (true) {
if (root1 != nullptr) {
stack1.push(root1);
root1 = root1->left;
}
else if (root2 != nullptr) {
stack2.push(root2);
root2 = root2->left;
}
else if (!stack1.empty() && !stack2.empty()) {
root1 = stack1.top();
root2 = stack2.top();
if (root1->data == root2->data) {
result.push_back(root1->data);
stack1.pop();
stack2.pop();
root1 = root1->right;
root2 = root2->right;
}
else if (root1->data < root2->data) {
stack1.pop();
root1 = root1->right;
root2 = nullptr;
}
else if (root1->data > root2->data) {
stack2.pop();
root2 = root2->right;
root1 = nullptr;
}
}
else {
break;
}
}
return result;
}
};