-
Notifications
You must be signed in to change notification settings - Fork 0
/
letcode_572_另一个树的子树.py
53 lines (43 loc) · 1.22 KB
/
letcode_572_另一个树的子树.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# -*- encoding: utf-8 -*-
"""
@File : letcode_572_另一个树的子树.py
@Time : 2020/9/16 下午3:15
@Author : dididididi
@Email :
@Software: PyCharm
"""
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
def same_tree(t1, t2):
if not t1 and not t2:
return True
elif not t1 or not t2:
return False
return t1.val == t2.val and same_tree(t1.left, t2.left) and same_tree(t1.right, t2.right)
if not s and not t:
return True
if not s or not t:
return False
return same_tree(s, t) or self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
if __name__ == '__main__':
sol = Solution()
# root = s = TreeNode(3)
s = TreeNode(3)
s.left = TreeNode(4)
s.right = TreeNode(5)
s.left.left = TreeNode(1)
s.left.right = TreeNode(2)
t = TreeNode(4)
t.left = TreeNode(1)
t.right = TreeNode(2)
print(sol.isSubtree(s, t))