判断某个二叉树是否为另外一个二叉树的子结构


思路

      先判断以当前根节点为根节点的二叉树是否和模板二叉树匹配。倘若不匹配。接着依次判断左右子树是否匹配

      匹配函数先比较根节点,若根节点相等,则匹配2者的左右子树


代码:

bool match(head1,head2)//匹配函数
{
    if(!head2)
	    return true;
    if(!head1)
	    return false;

    if(head1->value!=head2->value)
	    return false;
    else
	    return match(head1->left,head2->left)&&match(head1->right,head2->right);
}

bool subTree(Node* head1,Node head2)//主函数
{
           bool result=false;
	  
	  if(head1&&head2)
	     return match(head1,head2)||match(head1->left,head2)||match(head1->right,head2);
	  else
	     return result;
}


相关文章:

  • 2021-07-05
  • 2021-08-04
  • 2022-12-23
  • 2021-09-29
  • 2022-12-23
  • 2022-12-23
  • 2022-01-07
  • 2021-10-03
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-11-25
  • 2021-12-27
  • 2022-12-23
  • 2021-10-07
相关资源
相似解决方案