九度1820

测试案例挺坑的。

#include<stdio.h>
#include<iostream>

typedef struct binarytree{
	int m_nValue;
	binarytree *m_pLeft;
	binarytree *m_pRight;
}BinaryTree;

void CreateTree(BinaryTree *data[1002], int num);
bool SearchBfromA(BinaryTree *TreeA, BinaryTree *TreeB);
bool DoesAhaveB(BinaryTree *A, BinaryTree *B);
int main(){
	int m;
	int n;

	BinaryTree *TreeStructureA[1002];
	BinaryTree *TreeStructureB[1002];
	
	while(scanf("%d %d", &n, &m) != EOF){
		if( n < 0 || m <0 ){
			//printf("NO\n");
			continue;
		}
		if( n == 0 && m == 0){
			printf("NO\n");//这是测试案例3的 
			continue;
		}
		if( n != 0 && m == 0){
			printf("NO\n");
			continue;
		}
		if( n == 0 && m != 0){
		//	printf("NO\n");//这是测试案例4的 
			continue;
		}
		CreateTree(TreeStructureA, n);
		CreateTree(TreeStructureB, m);
		
		if(SearchBfromA(TreeStructureA[0], TreeStructureB[0])){
			printf("YES\n");
		}else{
			printf("NO\n");
		}
		
		

	}

	
	return 0;
} 
void CreateTree(BinaryTree *data[1002], int n){
	    if(n <= 0){
	    	return;
		}
		int datatmp;
	    int datal,datar;
	    int k; 
	    int i;

		for(i=0; i<n; i++){	
			scanf("%d", &datatmp);
			data[i] = new BinaryTree();
			data[i]->m_nValue = datatmp;
			
		}
	    
		for(i=0; i<n; i++){
			scanf("%d",&k);
			if(k == 2){
				scanf("%d %d", &datal, &datar);
			    data[i]->m_pLeft = data[datal-1];
			    data[i]->m_pRight = data[datar-1];
			    
			}else if(k == 1){
				scanf("%d", &datal);
				data[i]->m_pLeft = data[datal-1]; 
				data[i]->m_pRight = NULL;
			}else if(k == 0){
				data[i]->m_pLeft = NULL;
				data[i]->m_pRight = NULL;
			}
		}

}

bool SearchBfromA(BinaryTree *TreeA, BinaryTree *TreeB){
	bool result = false;
	
	if(TreeA != NULL && TreeB != NULL){
		if(TreeA->m_nValue == TreeB->m_nValue){
			result = DoesAhaveB(TreeA, TreeB);
		}
		if(!result){
			result = SearchBfromA(TreeA->m_pLeft, TreeB);
		}
		if(!result){
			result = SearchBfromA(TreeA->m_pRight, TreeB);
		}
	}
	
	return result;
}

bool DoesAhaveB(BinaryTree *A, BinaryTree *B){
	
	if(B == NULL && A != NULL){
		return true;
	}
	if(A == NULL && B != NULL){
		return false;
	}
	if(A == NULL && B == NULL){
		return true;
	}
	
	if(A->m_nValue != B->m_nValue){
		return false;
	}
	
	return DoesAhaveB(A->m_pLeft, B->m_pLeft) && DoesAhaveB(A->m_pRight,B->m_pRight);
	
	
	
	
}


你可能感兴趣的:(二叉树,九度)