方法:先用A创建 有序二叉树,然后用B中的数值依次在二叉树中寻找,如果找到了,就增加到交集数组中
复杂度:创建二叉树的复杂度logn,在二叉树中查找的复杂度是 logn*(m+1)
#include"stdio.h"
int commonArray[20];
int com_len=0;
struct node
{
int data;
struct node *lNode;
struct node *rNode;
};
struct node *head;
void printTree(struct node *p)
{
if(p)
{
printTree(p->lNode );
printf("%d ",p->data );
printTree(p->rNode );
}
}
struct node *createTree(int a[],int len)
{
struct node *curNode,*nextNode,*newNode;
int i=1;
if(len<=0)
return NULL;
head=(struct node *)malloc(sizeof(struct node *));
head->data =a[0];
head->lNode =NULL;
head->rNode =NULL;
while(i<len)
{
newNode=(struct node *)malloc(sizeof(struct node *));
newNode->data =a[i];
newNode->lNode =NULL;
newNode->rNode =NULL;
curNode=head;
if(head->data>a[i])
nextNode=head->lNode ;
else nextNode=head->rNode ;
while(nextNode)
{
curNode=nextNode;
if(curNode->data >a[i])
nextNode=curNode->lNode ;
else
nextNode=curNode->rNode ;
}
if(curNode->data >a[i])
curNode->lNode =newNode;
else
curNode->rNode =newNode;
i++;
}
return head;
};
int findValueInTree(struct node *p,int value)
{
int findValue=0;
if(p)
{
if(p->data ==value)
findValue=1;
else if(p->data >value)
findValue=findValueInTree(p->lNode ,value);
else
findValue=findValueInTree(p->rNode ,value);
}
return findValue;
}
//打印数组
void printArray(int *a,int len)
{
int i=0;
if(len<=0)
return;
for(;i<len;i++)
printf("%d ",a[i]);
printf("\n");
}
void findCommonArray(int *a,int a_len,int *b,int b_len)
{
int j=0;
head=createTree(a,a_len);//创建二叉树
for(;j<b_len;j++)
{
if(findValueInTree(head,b[j]))
commonArray[com_len++]=b[j];
}
printf("打印第一个数组\n");
printArray(a,a_len);
printf("打印第二个数组\n");
printArray(b,b_len);
printf("打印二个数字的交集\n");
printArray(commonArray,com_len);
// printTree(head);
}
int main()
{
int a[10]={5,0,8,7,9,6,33,22,30,88
};
int b[8]={0,-11,12,65,98,77,5,30
};
findCommonArray(a,10,b,8);
getchar();
return 0;
}