KMP algorithm - another tree subtree

Given two binary nonempty s and t, and the test is included in s t subtrees having the same structure and the node values. s of a subtree including all the descendants of a node and the node s. s can be seen as its own subtree.

Example 1:
given tree s:

3
/ \
45
/ \
12
given tree t:

4
/ \
12
returns true, since t and s in a sub-tree nodes have the same structure and values.

Example 2:
given tree s:

3
/ \
45
/ \
12
/
0
given tree t:

4
/ \
12
returns false.

/**
 * 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:
    void dfs_s(TreeNode* root, string &res){
        if(!root){
            res+='#';
            return;
        }
        res+='?'+to_string(root->val);
        dfs_s(root->left, res);
        dfs_s(root->right, res);
    }
    bool isSubtree(TreeNode* s, TreeNode* t) {
        string ss,tt;
        dfs_s(s,ss);
        dfs_s(t,tt);
        int n=tt.size();
        vector<int>ne(n);
        int j=-1;
        ne[0]=-1;
        for(int i=1;i<n;i++){
            while(j>-1&&tt[i]!=tt[j+1])j=ne[j];
            if(tt[i]==tt[j+1])j++;
            ne[i]=j;
        }
        j=-1;
        for(int i=0;i<ss.size();i++){
            while(j>-1&&ss[i]!=tt[j+1])j=ne[j];
            if(ss[i]==tt[j+1])j++;
            if(j==n-1)return true;
        }
        return false;
    }
};

 

Guess you like

Origin www.cnblogs.com/programyang/p/11267138.html