详细讲解请参考《剑指offer》.
题目描述:
输入两颗二叉树A,B,判断B是不是A的子结构。
代码实现:
#include <stdio.h>
#include <stdlib.h>
typedef struct TNode
{
int value;
TNode *lchild;
TNode *rchild;
}TNode,*BTree;
BTree creat_tree(int preOrder[],int startPre,int endPre,int inOrder[],int startIn,int endIn)
{
if((endPre - startPre) != (endIn - startIn))
return NULL;
if(startPre > endPre)
return NULL;
BTree tree = (BTree)malloc(sizeof(TNode));
tree->value = preOrder[startPre];
tree->lchild = NULL;
tree->rchild = NULL;
if(startPre == endPre)
return tree;
int index,length;
for(index = startIn;index < endIn;index++)//
if(preOrder[startPre] == inOrder[index]) break;
//有左子树
if(index > startPre)
{
length = index - startPre;
tree->lchild = creat_tree(preOrder,startPre+1,startPre+length,inOrder,startIn,startIn+length-1);
}
//有右子树
if(index < endIn)
{
length = endIn - index;
tree->rchild = creat_tree(preOrder,endPre-length+1,endPre,inOrder,endIn-length+1,endIn);
}
return tree;
}
//后序遍历二叉树
void postTraverse(BTree tree)
{
if(tree->lchild != NULL) postTraverse(tree->lchild);
if(tree->rchild != NULL) postTraverse(tree->rchild);
printf("%d\t",tree->value);
}
//判断树A中以R为根节点的子树是不是和树B具有相同的结点
bool DoesTree1HaveTree2(BTree pRoot1,BTree pRoot2)
{
if(pRoot2 == NULL) //第二个二叉树pRoot2为空时,说明pRoot2是第一棵二叉树的pRoot1的子结构,返回true
return true;
if(pRoot1 == NULL) //当pRoot1为空时,此时pRoot2还没为空,说明pRoot2不是pRoot1的子结构,返回false。
return false;
if(pRoot1->value != pRoot2->value) //当前跟节点不相等,返回false
return false;
return DoesTree1HaveTree2(pRoot1->lchild,pRoot2->lchild) && //递归比较左右子树
DoesTree1HaveTree2(pRoot1->rchild,pRoot2->rchild);
}
//在树A中查找与树B种根节点值一样的结点
bool HasSubTree(BTree pRoot1,BTree pRoot2)
{
bool result = false;
if(pRoot1 != NULL && pRoot2 != NULL)
{
if(pRoot1->value == pRoot2->value) //若找到,则进行第二步
result = DoesTree1HaveTree2(pRoot1,pRoot2);
if(!result && pRoot1->lchild!=NULL) //未找到 ,在A的左子树中继续查找
result = HasSubTree(pRoot1->lchild,pRoot2); //未找到 ,在B的左子树中继续查找
if(result!=NULL && pRoot1->rchild != NULL)
result = HasSubTree(pRoot1->rchild,pRoot2);
}
return result;
}
int main()
{
int preOrder[7] = {1,2,4,7,3,6,8};
int inOrder[7] = {4,7,2,1,3,8,6};
int preOrder0[3] = {14,2,3};
int inOrder0[3] = {2,14,3};
BTree tree1 = creat_tree(preOrder,0,6,inOrder,0,6);
postTraverse(tree1);
printf("\n");
BTree tree2 = creat_tree(preOrder0,0,2,inOrder0,0,2);
postTraverse(tree2);
printf("\n");
if(HasSubTree(tree1,tree2))
printf("tree2是tree1的子树");
else
printf("tree2不是tree1的子树");
printf("\n");
return 0;
}