|
| 1 | +# Subtree of Another Tree |
| 2 | +# https://leetcode.com/problems/subtree-of-another-tree/ |
| 3 | + |
| 4 | +# Definition for a binary tree node. |
| 5 | +# class TreeNode(object): |
| 6 | +# def __init__(self, val=0, left=None, right=None): |
| 7 | +# self.val = val |
| 8 | +# self.left = left |
| 9 | +# self.right = right |
| 10 | +class Solution(object): |
| 11 | + def sameTrees(self, t1, t2): |
| 12 | + # if we reach null node of both trees then return true |
| 13 | + if (not t1 and not t2): |
| 14 | + return True |
| 15 | + # if one tree has nodes, but another doesn't we return false |
| 16 | + if ((not t1) and t2): |
| 17 | + return False |
| 18 | + if (t1 and (not t2)): |
| 19 | + return False |
| 20 | + # if left sub tree is not the same we return False and early terminate. |
| 21 | + if not(self.sameTrees(t1.left, t2.left)): |
| 22 | + return False |
| 23 | + # if values are not same we reutrn false and early terminate without checking further. |
| 24 | + if (t1.val != t2.val): |
| 25 | + return False |
| 26 | + # if right sub tree is not the same we return false and early terminate |
| 27 | + if not(self.sameTrees(t1.right, t2.right)): |
| 28 | + return False |
| 29 | + # else we return true to keep looking further. |
| 30 | + return True |
| 31 | + |
| 32 | + def findSubTree(self, root, subRoot): |
| 33 | + # if it's a null node, we return back. |
| 34 | + if not root: |
| 35 | + return |
| 36 | + # if we find current node value = subTree root value we check if they are same or not |
| 37 | + if (root.val == subRoot.val): |
| 38 | + if (self.sameTrees(root, subRoot)): |
| 39 | + return True |
| 40 | + # if sub tree found in left sub tree we return true and early terminate. |
| 41 | + if (self.findSubTree(root.left, subRoot)): |
| 42 | + return True |
| 43 | + # if sub tree found in right sub tree we return true and early teminate |
| 44 | + if (self.findSubTree(root.right, subRoot)): |
| 45 | + return True |
| 46 | + |
| 47 | + def isSubtree(self, root, subRoot): |
| 48 | + return self.findSubTree(root, subRoot) |
| 49 | + """ |
| 50 | + :type root: TreeNode |
| 51 | + :type subRoot: TreeNode |
| 52 | + :rtype: bool |
| 53 | + """ |
0 commit comments