剑指offer中判断树的子结构的题
题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)题目链接:https://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88?tpId=13&tqId=11170&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
以下是我的思路,无论A,B通过何种遍历,只要B是A的子结构的话,B的遍历顺序应该与在A中的相同。没能通过用例,我自己在visual studio中检验过while循环可以正确地判断B是不是A的子串。麻烦各位帮我看一下,哪里出错了呢?
class Solution {
//中序遍历void Intrav(TreeNode *r, vector<int> &v)
{
if(r != NULL)
{
Intrav(r->left, v);
v.push_back(r->val);
Intrav(r->right,v);
}
else return;
}
public:
bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
if(pRoot1==NULL||pRoot2==NULL)
return false;
//否则遍历两树
vector<int> ivec1;
vector<int> ivec2;
Intrav(pRoot1,ivec1);
Intrav(pRoot2,ivec2);
int length=ivec2.size();
//先在ivec1中查找出ivec2首个元素的位置
int i=0;
while(i<ivec1.size())
{
if(ivec1[i]==ivec2[0])//若在树1的中序遍历中的第i个位置找到了树2的根
{
int indexofvec2=1;
for(int j=i+1;j<i+length;++j)//跳过树2的第一个点,逐个比较后面的点
{
if(ivec1[j]!=ivec2[indexofvec2++])
return false;
}
return true;//
}
else
++i;
}
return false;
}
};
#C/C++#