1
+ """
2
+ We use DFS to traverse `s`. (Or you can use BFS)
3
+ If we encounter a node and `node.val==t.val`.
4
+ We check if the node and t are the same tree, using `isSameTree()`.
5
+
6
+ In `isSameTree()` we use BFS to traverse both tree to check if they are exactly the same.
7
+ We use BFS because. If some nodes are not the same, we can return early at higher level.
8
+ Do need to go deep. Imagine the node that is not the same is at the bottom of the tree...
9
+
10
+ Time complexity is O(M*N). M is the number of nodes in s. N is the number of nodes in t.
11
+ Traversing s takes O(M).
12
+ `isSameTree()` takes O(N) to check all nodes in t.
13
+ In the worst case, we might need to execute `isSameTree()` on every node in s.
14
+
15
+ Space complexity is O(M+N), since we might store all the nodes in memory.
16
+ """
17
+ from collections import deque
18
+
19
+ class Solution (object ):
20
+ def isSubtree (self , s , t ):
21
+ def isSameTree (root1 , root2 ):
22
+ q1 = deque ([root1 ])
23
+ q2 = deque ([root2 ])
24
+ while q1 and q2 :
25
+ n1 = q1 .popleft ()
26
+ n2 = q2 .popleft ()
27
+ if n1 .val != n2 .val : return False
28
+ if n1 .left : q1 .append (n1 .left )
29
+ if n1 .right : q1 .append (n1 .right )
30
+ if n2 .left : q2 .append (n2 .left )
31
+ if n2 .right : q2 .append (n2 .right )
32
+
33
+ #check if both queue are empty.
34
+ #if both queue are empty, all nodes are checked.
35
+ return not q1 and not q2
36
+
37
+ stack = []
38
+ stack .append (s )
39
+ while stack :
40
+ node = stack .pop ()
41
+ if node .val == t .val and isSameTree (node , t ): return True
42
+ if node .left : stack .append (node .left )
43
+ if node .right : stack .append (node .right )
44
+ return False
0 commit comments