bool IsSubStructure(Node*T1, Node*T2)//whether T2 is substructure of T1
{
if(T2==NULL)//T2 null means all matched in T1
return true;
else if(T1==NULL)//T2 not null, T1 null, means not all matched in T1
return false;
else
{
if(T1->data==T2->data)//root data same, check whether each child are both same
return IsSubStructure(T1->left, T2->left)&& IsSubStructure(T1->right, T2->right);
else//root data not same, check whether T2 is substructure of T1 leftchild or rightchold
return IsSubstructure(T1->left,T2)||IsSubStructure(T1->right,T2);
}
}
昨天看到一到面试代码题,问T2是否T1得子树,结果查到了子结构的题目,关键是代码居然和博主的不谋而合,
http://blog.csdn.net/success041000/article/details/6729893
虽然写递归出口的时候有点纠结。这个代码有些情况可能处理不了,但是博主的代码1是可以处理的,只是有点繁。
非常感谢 @sumnous_t 大神的博客,和大神交流后总能学到很多。
突然发现稍微改一个地方好像,就可以处理之前不能处理的情况了,也即会遍历完所有的子树判断,同时也是递归,另外改成检测子树的
要稍微修改一下递归出口
bool IsSubBT(Node*T1, Node*T2)//whether T2 is subBT of T1
{
if(T1==NULL&&T2==NULL)//T1 T2 null means all matched
return true;
if((T1==NULL&&T2!=NULL)||(T1!=NULL&&T2==NULL))//T1, T2 one null, one not null, means not matched
return false;
if(T1->data==T2->data&& IsSubBT(T1->left, T2->left)&& IsSubBT(T1->right, T2->right))//root data same, each child are both same, return found
return true;
else//not find, check whether T2 is subBT of T1 leftchild or rightchold
return IsSubBT(T1->left,T2)||IsSubBT(T1->right,T2);
}