forked from netsetos/python_code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubtree.py
More file actions
52 lines (47 loc) · 1.35 KB
/
subtree.py
File metadata and controls
52 lines (47 loc) · 1.35 KB
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
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def isidentical(root1,root2):
if(root1 == None and root2 == None):
return True
if(root1 != None and root2 != None and root1.data == root2.data):
l = isidentical(root1.left , root2.left)
r = isidentical(root1.right, root2.right)
if(l and r):
return True
return False
return False
def issubtree(target,source):
if(source is None):
return True
if(target is None):
return False
if isidentical(target,source):
return True
else:
l=issubtree(target.left,source)
r=issubtree(target.right, source)
return l or r
target = Node('a')
target.left = Node('b')
target.right = Node('c')
target.right.left = Node('j')
target.right.right = Node('g')
target.left.left = Node('d')
target.left.right = Node('e')
target.left.left.left = Node('h')
target.left.left.right = Node('i')
target.left.right.right = Node('k')
target.right.right.right = Node('l')
target.right.right.left = Node('m')
source = Node('c')
source.left = Node('j')
source.right = Node('g')
# source.right.left = Node('z')
# source.right.right = Node('l')
if issubtree(target,source):
print("Subtree")
else:
print("Not a Subtree")