-
Notifications
You must be signed in to change notification settings - Fork 0
/
TUGAS TRAVERSAL POHON.py
101 lines (81 loc) · 2.43 KB
/
TUGAS TRAVERSAL POHON.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
from __future__ import print_function
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items==[]
def push(self,items):
self.items.append(items)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
class Binarytree:
def __init__(self,root):
self.key = root
self.leftChild = None
self.rightChild = None
def insertLeft(self,newNode):
if self.leftChild == None :
self.leftChild = Binarytree(newNode)
else :
t = Binarytree(newNode)
t.leftChild = self.leftChild
self.leftChild = t
def insertRight(self,newNode):
if self.rightChild == None :
self.rightChild = Binarytree(newNode)
else :
t = Binarytree(newNode)
t.rightChild = self.rightChild
self.rightChild = t
def getrightChild(self):
return self.rightChild
def getleftChild(self):
return self.leftChild
def getrootVal(self):
return self.key
def setrootVal(self,obj):
self.key = obj
def size(self):
count = 0
selfleft = self
selfright = self
while selfleft.getleftChild() != None or selfright.getrightChild() != None :
count += 1
if selfleft.getleftChild() != None:
selfleft = selfleft.getleftChild()
else :
selfright = selfright.getrightChild()
return count
def Inorder(root):
if root:
Inorder(root.getleftChild())
print(root.getrootVal(),end=" ")
Inorder(root.getrightChild())
def Preorder(root):
if root:
print(root.getrootVal(),end=" ")
Preorder(root.getleftChild())
Preorder(root.getrightChild())
def Postorder(root):
if root:
Postorder(root.getleftChild())
Postorder(root.getrightChild())
print(root.getrootVal(),end=" ")
root = Binarytree('DANI')
root.insertLeft('SANTI')
root.getleftChild().insertLeft('FANI')
root.getleftChild().insertRight('REKA')
root.getleftChild().getleftChild().insertLeft('WATI')
root.getleftChild().getrightChild().insertRight('HADI')
root.insertRight('AMA')
root.getrightChild().insertLeft("MAMI")
root.getrightChild().insertRight("CICA")
Inorder(root)
print ()
Preorder(root)
print ()
Postorder(root)