1
+ # Definition for a binary tree node.
2
+ class TreeNode (object ):
3
+ def __init__ (self , x ):
4
+ self .val = x
5
+ self .left = None
6
+ self .right = None
7
+
8
+
9
+ def build_bintree (s , i ):
10
+ if s :
11
+ node = TreeNode (s [i ])
12
+ if 2 * i + 1 < len (s ) and s [2 * i + 1 ]:
13
+ node .left = build_bintree (s , 2 * i + 1 )
14
+ if 2 * i + 2 < len (s ) and s [2 * i + 2 ]:
15
+ node .right = build_bintree (s , 2 * i + 2 )
16
+ return node
17
+
18
+ class Solution (object ):
19
+ def isSubtree (self , s , t ):
20
+ """
21
+ :type s: TreeNode
22
+ :type t: TreeNode
23
+ :rtype: bool
24
+ """
25
+ self .same_val_node = []
26
+ def _find_val (root , x ):
27
+ if root :
28
+ if root .val == x :
29
+ self .same_val_node .append (root )
30
+ _find_val (root .left , x )
31
+ _find_val (root .right , x )
32
+
33
+ def _same_tree (s , t ):
34
+ if not s and not t :
35
+ return True
36
+ if s and t :
37
+ if s .val == t .val :
38
+ return _same_tree (s .left , t .left ) and _same_tree (s .right , t .right )
39
+ return False
40
+
41
+ if not s and not t :
42
+ return True
43
+ if s and t :
44
+ _find_val (s , t .val )
45
+ if self .same_val_node :
46
+ return any (_same_tree (node , t ) for node in self .same_val_node )
47
+ return False
48
+
49
+
50
+ def main ():
51
+ s = Solution ()
52
+ src = build_bintree ([3 ,4 ,5 ,1 ,2 ], 0 )
53
+ target = build_bintree ([4 ,1 ,2 ], 0 )
54
+ print s .isSubtree (src , target )
55
+ print s .isSubtree (build_bintree ([1 ,1 ], 0 ), build_bintree ([1 ], 0 ))
56
+
57
+
58
+ if __name__ == '__main__' :
59
+ main ()
0 commit comments