Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Logic:
- isSubTree function will traverse the tree and where root->node of subtree matches with
- current node of tree,then fun will be called which will check for subtree after current
- node matches or not.
- T.C O(mn) m,n is no. of nodes in both trees.
- S.C O(n)
- */
- bool fun(Node *t,Node *s){
- if(!t && !s) return true;
- if(!t || !s) return false;
- if(t->data==s->data)
- return (fun(t->left,s->left) && fun(t->right,s->right));
- else return false;
- }
- class Solution
- {
- public:
- //Function to check if S is a subtree of tree T.
- bool isSubTree(Node* t, Node* s)
- {
- if(!t && !s) return true;
- if(!t || !s) return false;
- if(t->data==s->data && fun(t,s)) return true;
- return isSubTree(t->left,s) || isSubTree(t->right,s);
- }
- };
- //Method 2:
- /*
- TC O(n)
- SC O(m+n)
- find preorder and inorder of both tree and if preorder of subtree is subarray of actual tree && inorder of subtree
- is subarray of actual tree,return true else false;
- use KMP for string matching.
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement