Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * ListNode *next;
- * ListNode() : val(0), next(nullptr) {}
- * ListNode(int x) : val(x), next(nullptr) {}
- * ListNode(int x, ListNode *next) : val(x), next(next) {}
- * };
- */
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode() : val(0), left(nullptr), right(nullptr) {}
- * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
- * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
- * };
- */
- class Solution {
- public:
- int n;
- vector<int> list, lps;
- void convertListToArray(ListNode* head){
- n = 0;
- while(head){
- list.push_back(head->val);
- n++;
- head = head->next;
- }
- lps.resize(n+1);
- lps.assign(n+1, 0);
- }
- void kmpPreprocess(){
- int i, j;
- i=0; j=-1;
- lps[0] = -1;
- while(i<n){
- while(j>=0 && list[i] != list[j]) j = lps[j];
- i++, j++;
- lps[i] = j;
- }
- }
- bool kmpSearch(TreeNode* root, int i){
- if(i == n) return true;
- if(!root) return false;
- while(i>0 && root->val != list[i]) i = lps[i];
- if(root->val == list[i]) i++;
- return (kmpSearch(root->left, i) || kmpSearch(root->right, i));
- }
- bool isSubPath(ListNode* head, TreeNode* root) {
- convertListToArray(head);
- kmpPreprocess();
- return kmpSearch(root, 0);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment