树A包含树B的问题

有两棵树,要求验证树A包含树B




cat tree.c
#include <stdio.h>

typedef struct TreeNode{
int data;
struct TreeNode * lchild;
struct TreeNode * rchild;
}TNode;

//}TNode,*TNode *;


// A Tree B Tree
// 1 2
// / \ / \
// 2 3 4 5
// / \ \
// 4 5 6
// \
// 6

int a[]={1,2,4,0,6,0,0,5,0,0,3,0,0};
int b[]={2,4,0,6,0,0,5,0,0};

//int b[]={2,4,0,3,0,0,5,0,0}; // bu bao han ce shi BTree

int numA=0;
int numB=0;

int index=0;
int count=0;

TNode * CreateA(TNode * T){
int ch;
ch=a[numA];
numA++;
if(ch == 0){
T=NULL;
}else{
if(!(T=(TNode *)malloc(sizeof(TNode))))
printf("A in malloc error\n");
T->data = ch;
T->lchild = CreateA(T->lchild);
T->rchild = CreateA(T->rchild);
}
return T;
}


TNode * CreateB(TNode * T){
int ch;
ch=b[numB];
numB++;
if(ch == 0){
T=NULL;
}else{
if(!(T=(TNode *)malloc(sizeof(TNode))))
printf("B in malloc error\n");
T->data = ch;
T->lchild = CreateB(T->lchild);
T->rchild = CreateB(T->rchild);
}
return T;
}


void xianxu(TNode * T){
if(T!=NULL){
printf("%d\n",T->data);
xianxu(T->lchild);
xianxu(T->rchild);
}
}

void baohan(TNode * A,TNode * B){
if(A!=NULL && B!=NULL){
if(A->data != B->data){
baohan(A->lchild,B);
baohan(A->rchild,B);
}else{
index++;
baohan(A->lchild,B->lchild);
baohan(A->rchild,B->rchild);
}
}
}

void NodeCount(TNode * T){
if(T!=NULL){
count++;
NodeCount(T->lchild);
NodeCount(T->rchild);
}
}

int main(void){
TNode * rootA;
TNode * rootB;
rootA = CreateA(rootA);
rootB = CreateB(rootB);
printf("Create End \n");
printf("Tree A: \n");
xianxu(rootA);

printf("Tree B: \n");
xianxu(rootB);

printf("-----------------\n");
baohan(rootA,rootB);
NodeCount(rootB);

printf("AB same nodes count:%d TreeB,NodesCount :%d\n",index,count);
if(index==count)
printf("A baohan B\n");
else
printf("A bu baohan B\n");

return 0;

}


运行结果

Create End
Tree A:
1
2
4
6
5
3
Tree B:
2
4
3
5
-----------------
AB same nodes count:4 TreeB,NodesCount :4
A baohan B
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值