天天看點

04-樹4 是否同一棵二叉搜尋樹(25 分)

思路有三:

method_1:構造兩顆搜尋二叉樹在,然後逐一比較。

method_2:構造一顆二叉樹,另一組資料用來查找

method_3:直接比較兩個數組,遞歸。

我用的method_1:

#include <stdio.h>
#include <stdlib.h>
#include<malloc.h>

typedef int ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
    ElementType Data;
    BinTree Left;
    BinTree Right;
};

void judge( BinTree BT1,BinTree BT2,int *n) /* 先序周遊,由裁判實作,細節不表 */
{
	BinTree p1=BT1,p2=BT2;
	if(p1&&p2){
		if(p1->Data==p2->Data){
			(*n)++;
		    judge(p1->Left,p2->Left,n);
		    judge(p1->Right,p2->Right,n);
		}
	} 
} 
void prefree( BinTree BT) /* 先序周遊,由裁判實作,細節不表 */
{
	if(BT){
		prefree(BT->Left);
		prefree(BT->Right);
		free(BT);
	} 
} 
BinTree Insert( BinTree BST, ElementType X );

int main()
{
    int N,L,i,j;
    ElementType X;
    scanf("%d",&N);
	while(N)
	{
		scanf("%d",&L);
		BinTree BT1=NULL,BT2;
		for(i=0;i<N;i++){
			scanf("%d",&X);
			BT1=Insert(BT1,X);
		}
		for(i=0;i<L;i++){
			BT2=NULL;
			for(j=0;j<N;j++){   //建立搜尋二叉樹 
				scanf("%d",&X);
				BT2=Insert(BT2,X);
			}
			int n=0;
			judge(BT1,BT2,&n);
			prefree(BT2);
			if(n==N)printf("Yes\n");
			else printf("No\n");
		}
		prefree(BT1); 
		scanf("%d",&N);
	} 

    return 0;
}
BinTree Insert( BinTree BST, ElementType X )  //插入 
{
	BinTree p,pp,q=(BinTree)malloc(sizeof(BinTree));
	q->Data=X;q->Left=NULL;q->Right=NULL;
	if(!BST)BST=q;
	else{
		p=BST;
		while(p){
			if(X<p->Data){pp=p;p=p->Left;}
		    else{pp=p;p=p->Right;}
		}
		if(X<pp->Data)pp->Left=q;
		else pp->Right=q;
	} 
	return BST;
}
           

繼續閱讀