这个问题,在很多面试当中会出现。所谓子结构,就是子树结构是树结构的一部分。我们可以使用递归的方法来进行相应的处理与判断。
//树的子结构
struct tree
{
int value;
tree *left;
tree *right;
};
bool JudgeHas(tree *pRoot1, tree *pRoot2)
{
if (pRoot1 == NULL)//若大树为空,则必不是子树
return false;
if (pRoot2 == NULL)//若小树为空,则可以作为子树
return true;
if (pRoot1 -> value != pRoot2 -> value)//根不相同,则必不是子树
return false;
return JudgeHas(pRoot1->left, pRoot2->left)&&JudgeHas(pRoot1->right, pRoot2->right);//根相同时,继续左右子树的判断
}
bool FindSubTree(tree *pRoot1, tree *pRoot2)
{
bool result = false;//首先设定不是子结构
if(pRoot1 != NULL && pRoot2 != NULL)
{
if (pRoot1->value == pRoot2->value)//当某个节点相同时,
result = JudgeHas(pRoot1,pRoot2);//遍历分析以该节点为根的子树
if (!result)
result = FindSubTree(pRoot1->left,pRoot2);//如果根节点不相同,那么遍历左子树
if (!result)
result = FindSubTree(pRoot1->right,pRoot2);//如果根和左子树都不相同,遍历右子树
}
}