二叉树_另一棵树的子树
给你两棵二叉树tree1和tree2,检验tree1中是否包含和tree2具有相同结构和结点值的子树。如果存在,输出true;否则,输出false。
Input
第一行输入t,表示有t个测试样例。
第二行首先输入n1,接着输入n1个整数,表示二叉树tree1。
第三行首先输入n2,接着输入n2个整数,表示二叉树tree2。
以此类推,每两行输入一个测试样例,共输入t个测试样例。
数组形式的二叉树表示方法与题目:DS二叉树_伪层序遍历构建二叉树 相同,输入-1表示空结点。
Output
每一行输出当前测试样例是否符合题意。
共输出t行。
Sample
Input
5 5 3 4 5 1 2 3 4 1 2 10 3 4 5 1 2 -1 -1 -1 -1 0 3 4 1 2 5 3 4 5 1 2 5 50 4 60 1 2 1 3 1 3 7 1 2 2 3 4 3 3 3 2 3 3
Output
true false false true true
Hint
tree1结点数量 >= 1
tree2结点数量 >= 1
所有结点的值 >= 1
代码如下
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
class BiNode
{
public:
int data;
BiNode* lchild;
BiNode* rchild;
BiNode() :lchild(NULL), rchild(NULL) {}
BiNode(int a) :data(a), lchild(NULL), rchild(NULL) {}
~BiNode()
{
delete lchild;
delete rchild;
}
};
class BiTree
{
private:
BiNode* Root;
public:
BiTree() :Root(NULL) {}
~BiTree()
{
delete Root;
}
BiNode* levelCreate(int* a, int n)
{
BiNode* p = NULL;
queue<BiNode*> q;
int temp;
int i = 0;
temp = a[i];
i++;
if (temp != -1)
{
BiNode* t = new BiNode(temp);
p = t;
q.push(p);
}
while (!q.empty() && i < n)
{
BiNode* root = q.front();
temp = a[i];
if (temp != -1 && i < n)
{
BiNode* m = new BiNode(temp);
root->lchild = m;
q.push(m);
}
i++;
temp = a[i];
if (temp != -1 && i < n)
{
BiNode* m = new BiNode(temp);
root->rchild = m;
q.push(m);
}
i++;
q.pop();
}
return p;
}
bool issame(BiNode* tree1, BiNode* tree2)
{
if (tree1 == NULL && tree2 == NULL)
{
return true;
}
if (tree1 == NULL || tree2 == NULL)//上一个条件已经将都为NULL的情况筛选掉
{
return false;
}
if (tree1->data != tree2->data)
{
return false;
}
//当tree2的根节点与tree1的根节点匹配后,再检查它们的左右孩子是否相同,只有都相同才能返回true
return issame(tree1->lchild, tree2->lchild) && issame(tree1->rchild, tree2->rchild);
}
bool compare(BiNode* subroot, BiNode* mainroot) //subroot为子树,mainroot为主树
{
if (subroot == NULL)
{
return true;
}
if (mainroot == NULL) //注意不要忘记写主树为空的情况,不写会在遍历时报错!!!
{
return false;
}
if (issame(subroot, mainroot))
{
return true;
}
//若出现不匹配,则向下寻主树的左右子树,再与所给定的子树比较,使用“||”说明只要有一种符合即可
return compare(subroot, mainroot->lchild) || compare(subroot, mainroot->rchild);
}
};
int main()
{
int t;
cin >> t;
while (t--)
{
int n, m;
cin >> n;
int* arry = new int[n];
for (int i = 0; i < n; i++)
{
cin >> arry[i];
}
cin >> m;
int* temp = new int[m];
for (int j = 0; j < m; j++)
{
cin >> temp[j];
}
BiTree tree;
BiNode* tree1 = tree.levelCreate(arry, n);
BiNode* tree2 = tree.levelCreate(temp, m);
if (tree.compare(tree2, tree1))
{
cout << "true";
}
else
{
cout << "false";
}
cout << endl;
}
return 0;
}