Advertisement
imashutosh51

Check if subtree

Aug 4th, 2022
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. /*
  2. Logic:
  3. isSubTree function will traverse the tree and where root->node of subtree matches with
  4. current node of tree,then fun will be called which will check for subtree after current
  5. node matches or not.
  6.  
  7. T.C O(mn) m,n is no. of nodes in both trees.
  8. S.C O(n)
  9.  
  10. */
  11. bool fun(Node *t,Node *s){
  12.     if(!t && !s) return true;
  13.     if(!t || !s) return false;
  14.     if(t->data==s->data)
  15.        return (fun(t->left,s->left) && fun(t->right,s->right));
  16.     else return false;
  17. }
  18. class Solution
  19. {
  20.   public:
  21.     //Function to check if S is a subtree of tree T.
  22.     bool isSubTree(Node* t, Node* s)
  23.     {
  24.         if(!t && !s) return true;
  25.         if(!t || !s) return false;
  26.         if(t->data==s->data && fun(t,s)) return true;
  27.         return isSubTree(t->left,s) || isSubTree(t->right,s);
  28.     }
  29. };
  30.  
  31. //Method 2:
  32. /*
  33.  TC O(n)
  34.  SC O(m+n)
  35.  find preorder and inorder of both tree and if preorder of subtree is subarray of actual tree && inorder of subtree
  36.  is subarray of actual tree,return true else false;
  37.  use KMP for string matching.
  38.  
  39. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement