判断一棵树是否是另一棵树的子树(C语言版)

判断一棵树是否是另一棵树的子树:

#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       

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值