判断一棵树是否是另一棵树的子树:
#include <stdio.h>
struct TreeNode
{
int value;
struct TreeNode *left;
struct TreeNode *right;
};
int IsPart(struct TreeNode *root1,struct TreeNode *root2)
{
if (root2 == NULL)
return 1;
if (root1 == NULL)
return 0;
if (root1->value != root2->value)
return 0;
return IsPart(root1->left, root2->left)*IsPart(root1->right, root2->right);
}
int IsPartTree(struct TreeNode *root1,struct TreeNode *root2)//如果是则返回1,否则返回0
{
int result = 0;
if (root1 != NULL && root2 != NULL)
{
if (root1->value == root2->value)
result = IsPart(root1, root2);
if (!result)
result = IsPartTree(root1->left, root2);
if (!result)
result = IsPartTree(root1->right, root2);
}
return result;
}
struct TreeNode* createTree1()
{
struct TreeNode *root=(struct TreeNode *)malloc(sizeof(struct TreeNode)) ;
struct TreeNode *p1=(struct TreeNode *)malloc(sizeof(struct TreeNode)) ;
struct TreeNode *p2=(struct TreeNode *)malloc(sizeof(struct TreeNode)) ;
struct TreeNode *p3=(struct TreeNode *)malloc(sizeof(struct TreeNode)) ;
struct TreeNode *p4=(struct TreeNode *)malloc(sizeof(struct TreeNode)) ;
root->value=1;
p1->value=2;
p1->left=NULL;//注意这里叶子节点左右指针一定要置为NULL
p1->right=NULL;
p2->value=3;
p3->value=4;
p3->left=NULL;
p3->right=NULL;
p4->value=5;
p4->left=NULL;
p4->right=NULL;
root->left = p1;
root->right = p2;
p2->left = p3;
p2->right = p4;
return root;
}
struct TreeNode* createTree2()
{
struct TreeNode *root=(struct TreeNode *)malloc(sizeof(struct TreeNode));
struct TreeNode *p1=(struct TreeNode *)malloc(sizeof(struct TreeNode));
struct TreeNode *p2=(struct TreeNode *)malloc(sizeof(struct TreeNode));
root->value=1;
p1->value=2;
p1->left=NULL;
p1->right=NULL;
p2->value=3;
p2->left=NULL;
p2->right=NULL;
root->left = p1;
root->right = p2;
return root;
}
void deleteTree(struct TreeNode *root)
{
if (root != NULL)
{
free(root->left);
free(root->right);
free(root);
root = NULL;
}
}
int main()
{
struct TreeNode *root1 = createTree1();
struct TreeNode *root2 = createTree2();
printf("%d",IsPartTree(root1, root2));
deleteTree(root1);
deleteTree(root2);
return 0;
}
运行结果:1
代表tree2是tree1的子树
在原作者基础上进行了改进,详见:http://www.cnblogs.com/kaituorensheng/p/4215688.html