题目
输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构)
B是A的子结构, 即 A中有出现和B相同的结构和节点值。
bool isSubStructure(TreeNode* A, TreeNode* B) {
if (B==NULL)
{
return false;
}
if (A==NULL)
{
return false;
}
if (A->data!=B->data)
{
return isSubStructure(A->left, B)|| isSubStructure(A->right, B);
}
else
{
return Dfs(A,B);
}
}
bool Dfs(TreeNode*A,TreeNode*B)
{
stack<TreeNode*> a;
stack<TreeNode*> b;
a.push(A);
b.push(B);
while (!b.empty())
{
TreeNode* head_b = b.top();
b.pop();
TreeNode* head_a = a.top();
a.pop();
if (head_b->data!=head_a->data)
{
return false;
}
if (head_b->left==NULL&&head_b->right!=NULL)
{
b.push(head_b->right);
if (head_a->right==NULL)
{
return false;
}
else
{
a.push(head_a->right);
}
}
else if (head_b->left != NULL && head_b->right== NULL)
{
b.push(head_b->left);
if (head_a->left == NULL)
{
return false;
}
else
{
a.push(head_a->left);
}
}
else if (head_b->left != NULL && head_b->right != NULL)
{
b.push(head_b->left);
b.push(head_b->right);
if (head_a->left == NULL|| head_a->right == NULL)
{
return false;
}
else
{
a.push(head_a->left);
a.push(head_a->right);
}
}
}
return true;
}