面试题28

来源:互联网 发布:平价散粉推荐知乎 编辑:程序博客网 时间:2024/06/06 18:41

树的子结构:输入两颗二叉树A和B,判断B是不是A的子结构

typedef struct Bnode {    int value;    struct Bnode *lchild, *rchild;}btree;int isSameSubStruct(btree *root,btree *zroot) {    int result = 0;    if (root != NULL&&zroot != NULL) {        if (root->value == zroot->value) {      //在root中查找与zroot根节点相同的结点            result = isSameStruct(root, zroot);        }        if (!result)            result =  isSameSubStruct(root->lchild, zroot);        if(!result)            result = isSameSubStruct(root->rchild, zroot);    }    return result;}int isSameStruct(btree *root, btree *zroot) {    //判断以zroot与root为根节点的树是否相同    if (zroot == NULL)        return 1;    if (root == NULL)        return 0;    if (root->value != zroot->value)        return 0;    return isSameStruct(root->lchild, zroot->lchild) && isSameStruct(root->rchild, zroot->rchild);}
0 0
原创粉丝点击