imashutosh51

Check if subtree

Aug 4th, 2022 (edited)
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.14 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. def fun(root, sub):
  12.     if not root and not sub:
  13.         return True
  14.  
  15.     if not root or not sub:
  16.         return False
  17.  
  18.     if root.data != sub.data:
  19.         return False
  20.  
  21.     return fun(root.left, sub.left) and fun(root.right, sub.right)
  22.  
  23.  
  24. class Solution:
  25.     def isSubTree(self, t, s):
  26.         if not s:
  27.             return True
  28.         if not t:
  29.             return False
  30.  
  31.         a = False
  32.         if t.data == s.data:
  33.             a = fun(t, s)
  34.  
  35.         b = self.isSubTree(t.left, s)
  36.         c = self.isSubTree(t.right, s)
  37.  
  38.         return a or b or c
  39.  
  40.  
  41. //Method 2:
  42. /*
  43.  TC O(n)
  44.  SC O(m+n)
  45.  find preorder and inorder of both tree and if preorder of subtree is subarray of actual tree && inorder of subtree
  46.  is subarray of actual tree,return true else false;
  47.  use KMP for string matching.
  48. IT can work with Preorder + inorder and Inorder+Postorder also.
  49. */
Advertisement
Add Comment
Please, Sign In to add comment