020给定两个二叉树T1,T2判断T1是否是T2的子树(keep it up)

给定两个二叉树T1,T2判断T1是否是T2的子树
首先在T2中查找T1的根节点,如果找不到,
则T1不是T2的子树,如果能找到,我们可以
遍历T1,检查T1的每个结点是否对应的存在T2

中。

代码:

struct TreeNode
{
	int data;
	TreeNode* leftChild;
	TreeNode* rightChild;
};

bool isExited(const TreeNode* vRoot1, const TreeNode *vRoot2, TreeNode* vRes)
{
	if (vRoot1 == NULL) return false;

	if (vRoot2 == vRoot1) 
	{
		vRes = vRoot1;
		return true;
	}

	bool Flag = false;
	Flag = isExited(vRoot1, vRoot2->leftChild, vRes);
	if (!Flag)
	{
		Flag = isExited(vRoot1, vRoot2->rightChild, vRes);
	}
	return Flag;
}

bool isSame(const TreeNode* vRoot1, const TreeNode *vRoot2)
{
	if (vRoot1 == NULL && vRoot2 == NULL) return true;
	if (vRoot1 != vRoot2) return false;
	bool Flag = isSame(vRoot1->leftChild, vRoot2->leftChild);
	if (!Flag) return false;
	Flag = isSame(vRoot1->rightChild, vRoot2->rightChild);
	return Flag;
}

bool isSubTree(const TreeNode* vRoot1, const TreeNode *vRoot2)
{
	TreeNode* Temp = NULL; //保存在T2中的位置
	if (!isExited(vRoot1, vRoot2, Temp)) return false;
	return isSame(vRoot1, Temp);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值