题目:输入两棵二叉树A和B,判断树B是不是A的子结构。
思路:主要分两步:第一步)在树A中找到和B的根结点的值一样的结点;第二步)再判断树A中以该节点为根结点的子树是不是包括和树B一样的结构。这可用递归来解决。
struct BinaryTreeNode { //二叉树节点定义
int value;
BinaryTreeNode *left;
BinaryTreeNode *right;
}
bool isTreeAcontainsTreeB(BinaryTreeNode *root1,BinaryTreeNode *root2){
if(root1 == NULL)
return false;
if(root2 == NULL)
return true;
if(root1->value != root2->value)
return false;
return isTreeAcontainsTreeB(root1->left,root2->right) && isTreeAcontainsTreeB(root1->right,root2->right);
}
bool hasSubTreeCore(BinaryTreeNode *root1,BinaryTreeNode *root2){
bool flag = false;
if(root1->value == root2->value)
flag = isTreeAcontainsTreeB(root1,root2);
if(!flag && root1->left != NULL)
flag = isTreeAcontainsTreeB(root1->left,root2);
if(!flag && root2->right != NULL)
flag = isTreeAcontainsTreeB(root1->right,root2);
return flag;
}
bool hasSubTree(BinaryTreeNode *root1,BinaryTreeNode *root2){
if((root1 != NULL && root2 == NULL)||(root1 == NULL && root2 != NULL))
return false;
if(root1 == NULL && root2 == NULL)
return true;
return hasSubTreeCore(root1,root2);
}