LintCode Q245 Subtree in Python

  • Jinhai ZHOU
  • 6 Minutes
  • 2017年2月5日
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
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
# @param T1, T2: The roots of binary tree.
# @return: True if T2 is a subtree of T1, or false.
def isSubtree(self, T1, T2):
# write your code here
if T1 is None and T2 is None:
return True
elif T1 is not None and T2 is None:
return True
elif T1 is None and T2 is not None:
return False
else: # T1 and T2 are not None
if T1.val == T2.val: # T2.val == T1.val
return (self.isSame(T1.right, T2.right) and self.isSame(T1.left, T2.left)) or (self.isSubtree(T1.right, T2) or self.isSubtree(T1.left, T2))
else:
return self.isSubtree(T1.right, T2) or self.isSubtree(T1.left, T2)
def isSame(self, T1, T2):
if T1 is None and T2 is None:
return True
elif T1 is not None and T2 is None:
return False
elif T1 is None and T2 is not None:
return False
else: # T1 and T2 are not None
if T1.val == T2.val: # T2.val == T1.val
return (self.isSame(T1.right, T2.right) and self.isSame(T1.left, T2.left))
else:
False
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。