-
题目描述:
-
输入两颗二叉树A,B,判断B是不是A的子结构。
-
输入:
-
输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行一个整数n,m(1<=n<=1000,1<=m<=1000):n代表将要输入的二叉树A的节点个数(节点从1开始计数),m代表将要输入的二叉树B的节点个数(节点从1开始计数)。接下来一行有n个数,每个数代表A树中第i个元素的数值,接下来有n行,第一个数Ki代表第i个节点的子孩子个数,接下来有Ki个树,代表节点i子孩子节点标号。接下来m+1行,与树A描述相同。
-
输出:
-
对应每个测试案例,
若B是A的子树输出”YES”(不包含引号)。否则,输出“NO”(不包含引号)。
-
样例输入:
-
7 3 8 8 7 9 2 4 7 2 2 3 2 4 5 0 0 2 6 7 0 0 8 9 2 2 2 3 0 0 1 1 2 0 3 0
#include <cstdio> #include <iostream> #include <list> using namespace std; struct Node{ int x; struct Node *left; struct Node *right; }; Node *creat(int n){ int k,a; Node *ps[1002]; ps[1] = NULL; for(int i = 1;i <= n;i++){ Node *p = new Node; p->left = p->right = NULL; scanf("%d",&p->x); ps[i] = p; } for(int i = 1;i <= n;i++){ scanf("%d",&k); while(k--){ scanf("%d",&a); if(!ps[i]->left) ps[i]->left = ps[a]; else ps[i]->right = ps[a]; } } return ps[1]; } bool DoesTree1HaveAllNodesOfTree2(Node* pTreeHead1, Node* pTreeHead2) { if(pTreeHead2 == NULL) return true; if(pTreeHead1 == NULL) return false; if(pTreeHead1->x != pTreeHead2->x) return false; return DoesTree1HaveAllNodesOfTree2(pTreeHead1->left, pTreeHead2->left) && DoesTree1HaveAllNodesOfTree2(pTreeHead1->right, pTreeHead2->right); } bool HasSubtreeCore(Node* pTreeHead1, Node* pTreeHead2) { bool result = false; if(pTreeHead1->x == pTreeHead2->x) { result = DoesTree1HaveAllNodesOfTree2(pTreeHead1, pTreeHead2); } if(!result && pTreeHead1->left != NULL) result = HasSubtreeCore(pTreeHead1->left, pTreeHead2); if(!result && pTreeHead1->right != NULL) result = HasSubtreeCore(pTreeHead1->right, pTreeHead2); return result; } bool HasSubtree(Node* pTreeHead1, Node* pTreeHead2) { if(pTreeHead1 && pTreeHead2) return HasSubtreeCore(pTreeHead1, pTreeHead2); else return false; } int main(int argc, char const *argv[]) { int n,m; Node *root1,*root2; while(scanf("%d %d",&n,&m) != EOF){ root1 = creat(n); root2 = creat(m); if(HasSubtree(root1,root2)) printf("YES\n"); else printf("NO\n"); } return 0; }