Time O(n) ... Space O(n)
a good answer:
void dups(node* a, node* b)
{
if(!a || !b)
return;
stack<node*> p,q;
node* n1 = a, *n2 = b;
while(true)
{
if(n1)
{
p.push(n1);
n1 = n1->left;
}
else if(n2)
{
q.push(n2);
n2 = n2->left;
}
else if (!p.empty() && !q.empty())
{
n1 = p.top();
n2 = q.top();
if(n1->data < n2->data)
{
p.pop();
n1 = n1->right;
n2 = NULL;
}
else if(n2->data < n1->data)
{
q.pop();
n2 = n2->right;
n1 = NULL;
}
else
{
cout<<n1->data<<" ";
p.pop();
q.pop();
n1 = n1->right;
n2 = n2->right;
}
}
else
break;
}
}
//a recursive one
void intersect(node* a, node* b) {
if (!a || !b) return;
if (a->value < b->value) {
intersect(a, b->left);
intersect(a->right, b);
}
else if (a->value > b->value) {
intersect(a->left, b);
intersect(a, b->right);
}
if (a->value == b->value) {
printf("%d ", a->value);
intersect(a->left, b->left);
intersect(a->right, b->right);
}
}
No comments:
Post a Comment