您的位置:首页 > 理论基础 > 数据结构算法

判断一棵二叉树中是否包含另一棵二叉树

2016-09-25 08:37 561 查看
以下内容经过实际上机测试,如有不对,请指正,谢谢

#include <stdio.h>
#include <stdlib.h>
#define bool int
#define true 1
#define false 0
typedef struct BinaryTreeNode{
int value;
struct BinaryTreeNode *pLeft;
struct BinaryTreeNode *pRight;
}BinaryTreeNode;
BinaryTreeNode *createTree()//先序序列建立二叉树,输入-1代表当前节点为空
{
BinaryTreeNode *treeRoot;
int num;
printf("请输入当前节点的值:\n");
scanf("%d",&num);
if(num == -1)
treeRoot = NULL;
else
{
treeRoot = (BinaryTreeNode *)malloc(sizeof(BinaryTreeNode));
treeRoot->value = num;
printf("目前为左子树节点");
treeRoot->pLeft = createTree();
printf("目前为右子树节点");
treeRoot->pRight = createTree();
}
return treeRoot;
}
void xxBL(BinaryTreeNode *treeRoot) //先序遍历二叉树
{
if(treeRoot)
{
printf("%d ",treeRoot->value);
xxBL(treeRoot->pLeft);
xxBL(treeRoot->pRight);
}
}
bool hasSubTree(BinaryTreeNode *pRoot1, BinaryTreeNode *pRoot2)
{
bool result = false;
if(pRoot1 != NULL && pRoot2 != NULL)
{
if(pRoot1->value == pRoot2->value)
result = DoesTree1HaveTree2(pRoot1,pRoot2);
if(!result)
result = hasSubTree(pRoot1->pLeft,pRoot2);
if(!result)
result = hasSubTree(pRoot1->pRight,pRoot2);
}
return result;
}
bool DoesTree1HaveTree2(BinaryTreeNode *pRoot1, BinaryTreeNode *pRoot2)
{
if(pRoot2 == NULL)
return true;
if(pRoot1 == NULL)
return false;
if(pRoot1->value != pRoot2->value)
return false;
if(pRoot1->value == pRoot2->value)
return DoesTree1HaveTree2(pRoot1->pLeft,pRoot2->pLeft)
&& DoesTree1HaveTree2(pRoot1->pRight,pRoot2->pRight);
}
int main()
{
BinaryTreeNode *root1 = createTree();
/*
printf("二叉树的先序遍历序列为:\n");
xxBL(root);
*/
BinaryTreeNode *root2 = createTree();
bool bl = hasSubTree(root1,root2);
printf("%d",bl);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐