-
Notifications
You must be signed in to change notification settings - Fork 0
/
trees5.py
61 lines (44 loc) · 1.23 KB
/
trees5.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
class Node:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
#Inserting into tree
def Insert_data(self,data):
if(self.data!=None):
if(data<self.data):
if(self.left==None):
self.left=Node(data)
else:
self.left.Insert_data(data)
elif(data>self.data):
if(self.right==None):
self.right=Node(data)
else:
self.right.Insert_data(data)
else:
self.data=data
#Preorder Traversal
def Preorder(self,ele):
preorder=[]
if(ele!=None):
preorder.append(ele.data)
preorder=preorder+self.Preorder(ele.left)
preorder=preorder+self.Preorder(ele.right)
return preorder
#Print the tree
def Print(self):
if self.left:
self.left.Print()
print(self.data)
if self.right:
self.right.Print()
p=Node(5)
p.Insert_data(6)
p.Insert_data(1)
p.Insert_data(10)
p.Print()
print("Preorder Traversal")
res=p.Preorder(p)
for i in res:
print(i,end=" ")