-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Tree
116 lines (99 loc) · 2.38 KB
/
Binary Tree
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#Binary Tree
from collections import deque
class Node:
def __init__(self,val):
self.data=val
self.rchild=None
self.lchild=None
class BinaryTree:
def __init__(self):
self.root=None
def isempty(self):
return self.root==None
def display(self):
self.display1(self.root,0)
print()
def display1(self,p,level):
if p is None:
return
self.display1(p.rchild,level+1)
print()
for i in range(level):
print(" ",end='')
print(p.data)
self.display1(p.lchild,level+1)
def pre(self):
self.preorder(self.root)
print()
def preorder(self,p):
if p is None:
return
print(p.data," ",end='')
self.preorder(p.lchild)
self.preorder(p.rchild)
def inn(self):
self.inorder(self.root)
print()
def inorder(self,p):
if p is None:
return
self.inorder(p.lchild)
print(p.data," ",end='')
self.inorder(p.rchild)
def post(self):
self.postorder(self.root)
print()
def postorder(self,p):
if p is None:
return
self.postorder(p.lchild)
self.postorder(p.rchild)
print(p.data," ",end='')
def level(self):
if self.root is None:
print("Tree is empty!!")
qu=deque()
qu.append(self.root)
while len(qu)!=0:
p=qu.pop()
print(p.data," ",end='')
if p.lchild is not None:
qu.append(p.lchild)
if p.rchild is not None:
qu.append(p.rchild)
def height(self):
return self.height1(self.root)
def height1(self,p):
if p is None:
return 0
hl=self.height1(p.lchild)
hr=self.height1(p.rchild)
if hl > hr:
return(1+hl)
else:
return(1+hr)
def create(self):
self.root=Node('A')
self.root.lchild=Node('B')
self.root.rchild=Node('C')
self.root.lchild.lchild=Node('D')
self.root.lchild.rchild=Node('E')
self.root.rchild.rchild=Node('F')
BT=BinaryTree()
BT.create()
BT.display()
print("PREORDER: ")
BT.pre()
print()
print("INORDER: ")
BT.inn()
print()
print("POSTORDER: ")
BT.post()
print()
print("LEVELS: ")
BT.level()
print()
print("HEIGHT: ")
BT.height()
print()