#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
/***************************************************
* 函数功能:A 是否为B的子结构
* 参数说明
* 输入参数:
* 输出参数:
* 复杂性分析:时间复杂度:O(n*m),空间复杂度:O(1)
* 题目来源 :
* 日期:2018-08-06-15.52
***************************************************/
bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
if(pRoot1==NULL || pRoot2==NULL) return false;
return (isSubtree(pRoot1,pRoot2) || isSubtree(pRoot1->left,pRoot2) || isSubtree(pRoot1->right,pRoot2));
}
/***************************************************
* 函数功能:A 是否为B的子树
* 参数说明
* 输入参数:
* 输出参数:
* 复杂性分析:时间复杂度:O(n),空间复杂度:O(n)
* 题目来源 :
* 日期:2018-08-06-15.52
***************************************************/
bool HasSubTree(TreeNode* pRoot1,TreeNode* pRoot2)
{
if(pRoot1==NULL ||pRoot2==NULL) return false;
string STR="";
string match="";
Tree_to_string(pRoot1,STR);
Tree_to_string(pRoot2,match);
if(STR.size()<match.size()) return false;
int R=match.size();
int pos=0;
for(int i=0;i<STR.size();)
{
if(STR[i]!=match[pos])
{
int k=match.size()-1;
while(k>0 && STR[R]!=match[k])
{
k--;
}
i=R-k;
pos=0;
R=i+match.size();
}else
{
if(pos==match.size()-1)
{
return true;
}
pos++;
i++;
}
}
return false;
}
private:
bool isSubtree(TreeNode* root1,TreeNode* root2)
{
if(root2==NULL) return true;
if(root1==NULL) return false;
if(root1->val != root2->val)
{
return false;
}
return (isSubtree(root1->left,root2->left) && isSubtree(root1->right,root2->right));
}
void Tree_to_string(TreeNode* root,string& result)
{
if(root==NULL)
{
result+="#!";
return ;
}
result+=to_string(root->val)+'!';
Tree_to_string(root->left,result);
Tree_to_string(root->right,result);
}
};
int main()
{
TreeNode a1(5);
TreeNode b1(4);
TreeNode b2(3);
TreeNode c1(7);
TreeNode c2(6);
TreeNode c3(4);
TreeNode d1(8);
TreeNode d2(4);
TreeNode d3(6);
TreeNode d4(1);
a1.left=&b1;
a1.right=&b2;
b1.left=&c1;
b1.right=&c2;
b2.left=&c3;
c1.left=&d1;
c1.right=&d2;
c2.left=&d3;
c2.right=&d4;
Solution s;
cout<<s.HasSubTree(&a1,&c2)<<endl;
return 0;
}