输入两颗二叉树A,B,判断B是不是A的子结构。
递归分治
#include <cstdio>
#include <cstdlib>
#include <string>
#include <iostream>
#include <queue>
#include <queue>
#include <cstring>
#include <stack>
#include <cmath>
#include <algorithm>
#include <vector>
#if(defined(_WIN32) || defined(__WIN32__))
typedef __int64 LL;
typedef unsigned __int64 ULL;
#define ll I64
#else
typedef long long LL;
typedef unsigned long long ULL;
#define I64 ll
#endif
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
char str[40];
int g = 0;
int len;
TreeNode * construct(){
if(g == len)
return NULL;
if(str[g] == '#')
{
g++;
return NULL;
}
TreeNode *p = new TreeNode(str[g++]-'0');
p->left = construct();
p->right = construct();
return p;
}
bool is(TreeNode*p, TreeNode*q){
if(q == NULL)
return true;
if(p == NULL)
return false;
if(p->val == q->val)
return is(p->left, q->left) && is(p->right, q->right);
return false;
}
bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
if(pRoot1 == NULL || pRoot2 == NULL)
return false;
return is(pRoot1, pRoot2) || HasSubtree(pRoot1->left, pRoot2) || HasSubtree(pRoot1->right, pRoot2);
}
int main(void){
strcpy(str, "88792####4");
g = 0;
len = strlen(str);
TreeNode*p = construct();
strcpy(str, "892");
g = 0;
len = strlen(str);
TreeNode*q = construct();
cout<<HasSubtree(p, q)<<endl;
return 0;
}