-
Notifications
You must be signed in to change notification settings - Fork 134
/
Is_SubTree.py
64 lines (48 loc) · 1.28 KB
/
Is_SubTree.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
57
58
59
60
61
62
63
64
# Given two binary trees, check if the first tree is subtree of the second one.
# A Binary Tree node
class Node:
# Constructor to initialise node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def store_in_order(root, arr):
if root is None:
arr.append('$')
return
store_in_order(root.left, arr)
arr.append(root.data)
store_in_order(root.right, arr)
def store_pre_order(root, arr):
if root is None:
arr.append('$')
return
store_pre_order(root.left, arr)
store_pre_order(root.right, arr)
arr.append(root.data)
def isSubTree(t1, t2):
order_t1 = []
order_t2 = []
store_in_order(t1, order_t1)
store_in_order(t2, order_t2)
if ''.join(order_t1).find(''.join(order_t2)) == -1:
return False
order_t1 = []
order_t2 = []
store_pre_order(t1, order_t1)
store_pre_order(t2, order_t2)
if ''.join(order_t1).find(''.join(order_t2)) == -1:
return False
return True
T = Node('a')
T.left = Node('b')
T.right = Node('d')
T.left.left = Node('c')
T.left.right = Node('e')
S = Node('b')
S.left = Node('c')
S.right = Node('e')
if isSubTree(T, S):
print('Yes, S is a subtree of T')
else:
print('No, S is not a subtree of T')