一、题目描述
给你两棵二叉树tree1和tree2,检验tree1中是否包含和tree2具有相同结构和结点值的子树。如果存在,输出true;否则,输出false。
二、输入与输出
1.输入
第一行输入t,表示有t个测试样例。
第二行首先输入n1,接着输入n1个整数,表示二叉树tree1。
第三行首先输入n2,接着输入n2个整数,表示二叉树tree2。
以此类推,每两行输入一个测试样例,共输入t个测试样例。
数组形式的二叉树表示方法与题目:DS二叉树_伪层序遍历构建二叉树 相同,输入-1表示空结点。
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
2.输出
每一行输出当前测试样例是否符合题意。
共输出t行。
true
false
false
true
true
三、参考代码
#include <iostream>
#include <string>
#include<stack>
#include<queue>
using namespace std;
class TreeNode
{
public:
int data;
TreeNode* lchild;
TreeNode* rchild;
TreeNode* parent;
TreeNode() {};
TreeNode(int num) { parent = NULL, rchild = NULL; lchild = NULL; data = num; }
};
TreeNode* Create(int arr[], int num)
{
if (num == 0)
{
return NULL;
}
queue<TreeNode*> q;
TreeNode* root = new TreeNode(arr[0]);
q.push(root);
int index = 1;
while (!q.empty() && index < num)
{
TreeNode* now = q.front();
q.pop();
if (index < num && arr[index] != -1)
{
now->lchild = new TreeNode(arr[index]);
q.push(now->lchild);
}
index++;
if (index < num && arr[index] != -1)
{
now->rchild = new TreeNode(arr[index]);
q.push(now->rchild);
}
index++;
}
return root;
}
bool ee(TreeNode* t1, TreeNode* t2)
{
if (!t1 && !t2)//00
{
return true;
}
if (!t1 || !t2)//10 01
{
return false;
}
if (t1->data != t2->data)// 11
{
return false;
}
return ee(t1->lchild, t2->lchild) && ee(t1->rchild, t2->rchild);
}
bool pri(TreeNode* r, TreeNode* cr)
{
if (!r && !cr)//00
{
return false;
}
if (r == NULL)
{
return false;
}
if (ee(r, cr))
{
return true;
}
return pri(r->lchild, cr) || pri(r->rchild, cr);
}
int main()
{
int sum;
cin >> sum;
int num1 = 0;
int num2 = 0;
int flag = 0;
while (sum--)
{
cin >> num1;
int* arr1 = new int[num1];
for (int i = 0; i < num1; i++)
{
cin >> arr1[i];
}
TreeNode* t1 = Create(arr1, num1);
cin >> num2;
int* arr2 = new int[num2];
for (int i = 0; i < num2; i++)
{
cin >> arr2[i];
}
TreeNode* t2 = Create(arr2, num2);
if (pri(t1, t2))
{
cout << "true" << endl;
}
else
{
cout << "false" << endl;
}
}
return 0;
}