Skip to content

Commit 6952b38

Browse files
committed
solve: subtreeOfAnotherTree
1 parent 2af9e60 commit 6952b38

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

subtree-of-another-tree/yolophg.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Time Complexity: O(m * n) m: number of nodes in root, n: number of nodes in subRoot, n: number of nodes in subRoot - might call the check function (which is O(n)) on every node in root.
2+
# Space Complexity: O(n) - use a queue for BFS that can hold up to O(n) nodes in the worst case.
3+
4+
class Solution:
5+
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
6+
if root is None:
7+
return False
8+
if subRoot is None:
9+
return True
10+
11+
# helper to compare two trees
12+
def check(node1, node2):
13+
if node1 is None and node2 is None:
14+
return True
15+
if node1 is None or node2 is None:
16+
return False
17+
if node1.val != node2.val:
18+
return False
19+
# check left and right recursively
20+
return check(node1.left, node2.left) and check(node1.right, node2.right)
21+
22+
# BFS through the main tree
23+
queue = [root]
24+
while queue:
25+
curr = queue.pop(0)
26+
# if value matches subRoot, check deeper
27+
if curr.val == subRoot.val:
28+
if check(curr, subRoot):
29+
return True
30+
# add child nodes to keep exploring
31+
if curr.left:
32+
queue.append(curr.left)
33+
if curr.right:
34+
queue.append(curr.right)
35+
36+
return False

0 commit comments

Comments
 (0)