File tree 1 file changed +68
-0
lines changed
1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Time: O(m * n), m is the number of nodes of s, n is the number of nodes of t
2
+ # Space: O(h), h is the height of s
3
+
4
+ # Given two non-empty binary trees s and t,
5
+ # check whether tree t has exactly the same structure and
6
+ # node values with a subtree of s.
7
+ # A subtree of s is a tree consists of a node in s and all of this node's descendants.
8
+ # The tree s could also be considered as a subtree of itself.
9
+ #
10
+ # Example 1:
11
+ # Given tree s:
12
+ #
13
+ # 3
14
+ # / \
15
+ # 4 5
16
+ # / \
17
+ # 1 2
18
+ # Given tree t:
19
+ # 4
20
+ # / \
21
+ # 1 2
22
+ # Return true, because t has the same structure and node values with a subtree of s.
23
+ # Example 2:
24
+ # Given tree s:
25
+ #
26
+ # 3
27
+ # / \
28
+ # 4 5
29
+ # / \
30
+ # 1 2
31
+ # /
32
+ # 0
33
+ # Given tree t:
34
+ # 4
35
+ # / \
36
+ # 1 2
37
+ # Return false.
38
+
39
+ # Definition for a binary tree node.
40
+ # class TreeNode(object):
41
+ # def __init__(self, x):
42
+ # self.val = x
43
+ # self.left = None
44
+ # self.right = None
45
+
46
+ class Solution (object ):
47
+ def isSubtree (self , s , t ):
48
+ """
49
+ :type s: TreeNode
50
+ :type t: TreeNode
51
+ :rtype: bool
52
+ """
53
+ def isSame (x , y ):
54
+ if not x and not y :
55
+ return True
56
+ if not x or not y :
57
+ return False
58
+ return x .val == y .val and \
59
+ isSame (x .left , y .left ) and \
60
+ isSame (x .right , y .right )
61
+
62
+ def preOrderTraverse (s , t ):
63
+ return s != None and \
64
+ (isSame (s , t ) or \
65
+ preOrderTraverse (s .left , t ) or \
66
+ preOrderTraverse (s .right , t ))
67
+
68
+ return preOrderTraverse (s , t )
You can’t perform that action at this time.
0 commit comments