-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0572_Subtree_Of_Another_Tree.py
56 lines (43 loc) · 1.4 KB
/
0572_Subtree_Of_Another_Tree.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
54
55
56
from unittest import TestCase, main
from datastructures.binarytree import TreeNode, binarytree
def isSubtree(s: TreeNode, t: TreeNode) -> bool:
if not t:
return True
if not s:
return False
if s.val == t.val and is_equal(s, t):
return True
return isSubtree(s.left, t) or isSubtree(s.right, t)
def is_equal(s: TreeNode, t: TreeNode) -> bool:
if not s and not t:
return True
if not s or not t:
return False
return s.val == t.val and is_equal(s.left, t.left) and is_equal(s.right, t.right)
class Test(TestCase):
def test_given_case_1(self):
self.assertTrue(isSubtree(
binarytree([3, 4, 5, 1, 2]),
binarytree([4, 1, 2])
))
def test_given_case_2(self):
self.assertFalse(isSubtree(
binarytree([3, 4, 5, 1, 2, None, None, None, None, 0]),
binarytree([4, 1, 2])
))
def test_empty_in_empty(self):
self.assertTrue(isSubtree(None, None))
def test_empty_in_single_node(self):
self.assertTrue(isSubtree(TreeNode(1), None))
def test_subtree_in_child(self):
self.assertTrue(isSubtree(
binarytree([1, 2, 3]),
TreeNode(2)
))
def test_not_found_in_tree(self):
self.assertFalse(isSubtree(
binarytree([1, 4, 5]),
TreeNode(3)
))
if __name__ == "__main__":
main()