Skip to content

Commit 532c978

Browse files
committed
solved subtree of another tree
1 parent 32deff5 commit 532c978

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Time complexity : O(n*m)
2+
# Space complexity : Space complexity: O(h) h is the height of the call stack during the recursive traversal.
3+
class Solution:
4+
def isSubtree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
5+
if not q:
6+
return True
7+
8+
if not p:
9+
return False
10+
11+
if self.isSameTree(p, q):
12+
return True
13+
14+
return self.isSubtree(p.left, q) or self.isSubtree(p.right, q)
15+
16+
def isSameTree(self, p, q) -> bool:
17+
if not p and not q:
18+
return True
19+
20+
if not p and q:
21+
return False
22+
23+
if p and not q:
24+
return False
25+
26+
if p.val != q.val:
27+
return False
28+
29+
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

0 commit comments

Comments
 (0)