面试题18:树的子结构
题目:输入两棵二叉树A和B,判断B是不是A的子结构。二叉树结点的定义如下:
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode *m_pleft;
BinaryTreeNode *m_pright;
};
BinaryTreeNode* BuyNode()//申请一个节点
{
BinaryTreeNode * s = (BinaryTreeNode *)malloc(sizeof(BinaryTreeNode));
if(s == NULL)
exit(1);
memset(s,0,sizeof(BinaryTreeNode));
return s;
}
BinaryTreeNode *CreateTree()//创建树
{
BinaryTreeNode *s = NULL;
int x;//结点
cout<<"输入结点:";
cin>>x;
if(x != -1)
{
s = BuyNode();
s->m_nValue = x;
s->m_pleft = CreateTree();
s->m_pright = CreateTree();
}
return s;
}
template<class Type>
const Type & Max(const Type &a,const Type &b)
{
return a>b?a:b;
}
//树的深度//左右子树中最高的那个再加一
int Depth(BinaryTreeNode *p)
{
if(p == NULL)
return 0;
else return Max(Depth(p->m_pleft),Depth(p->m_pright))+1;
}
void Print_K(BinaryTreeNode *ptr,int k)
{
if((ptr!=NULL && k==0))
{
cout<<ptr->m_nValue<<" ";
}
else if(ptr!=NULL)
{
Print_K(ptr->m_pleft,k-1);
Print_K(ptr->m_pright,k-1);
}
}
//打印第K层的所有节点
void Print_K_Item(BinaryTreeNode *ptr,int k)
{
if(ptr==NULL || k<0)
return;
Print_K(ptr,k);
cout<<endl;
}
void PrintTree(BinaryTreeNode *root)//按层次打印树
{
if(root != NULL)
{
for(int i=0;i<Depth(root);i++)
{
Print_K_Item(root,i);
}
}
}
//判断树A中以R为根节点的子树是不是和B具有相同的结构
bool DoesTree1HaveTree2(BinaryTreeNode *root1,
BinaryTreeNode *root2)
{
if(root2 == NULL)
return true;
if(root1 == NULL)
return false;
if(root1->m_nValue != root2->m_nValue)
return false;
return DoesTree1HaveTree2(root1->m_pleft,root2->m_pleft)
&& DoesTree1HaveTree2(root2->m_pright,root2->m_pright);
}
//在root1中查找与root2根结点一样的值
bool HasSubtree(BinaryTreeNode *root1,
BinaryTreeNode *root2)
{
bool result = false;
if(root1 != NULL && root2 != NULL )
{
if(root1->m_nValue == root2->m_nValue)
result = DoesTree1HaveTree2(root1,root2);
if(!result)
result = HasSubtree(root1->m_pleft,root2);
if(!result)
result = HasSubtree(root1->m_pright,root2);
}
return result;
}
1、当两个树都不为空的时候
int main()
{
BinaryTreeNode *root1 = CreateTree();
PrintTree(root1);
cout<<endl;
BinaryTreeNode *root2 = CreateTree();
PrintTree(root2);
if(HasSubtree(root1,root2))
cout<<"root2为root1的子结构:"<<endl;
else
cout<<"root2不是root1的子结构:"<<endl;
}
2、树A不为空,树B为空
int main()
{
BinaryTreeNode *root1 = CreateTree();
PrintTree(root1);
cout<<endl;
BinaryTreeNode *root2 = NULL;
if(HasSubtree(root1,root2))
cout<<"root2为root1的子结构:"<<endl;
else
cout<<"root2不是root1的子结构:"<<endl;
}