link
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> spre,tpre;
bool isSubtree(TreeNode* s, TreeNode* t) {
preorder(s,spre);
preorder(t,tpre);
vector<int> table(tpre.size());
int len=0;
for(int i=1;i<tpre.size();i++){
if(tpre[i]==tpre[len]){
len++;
table[i]=len;
}else{
if(len==0) {
table[i]=0;
}else{
len=table[len-1];
i--;
}
}
}
int i=0;
int j=0;
while(i<spre.size()){
if(spre[i]==tpre[j]){
i++;
j++;
if(j==tpre.size()) return true;
}else{
if(j==0){
i++;
}else{
j=table[j-1];
}
}
}
return false;
}
void preorder(TreeNode* t, vector<int>& vs){
if(t==nullptr) return;
vs.push_back(t->val);
if(t->left) preorder(t->left,vs);
else vs.push_back(INT_MIN);
if(t->right) preorder(t->right,vs);
else vs.push_back(INT_MAX);
}
};