-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeHeight.py
More file actions
67 lines (59 loc) · 1.53 KB
/
BinaryTreeHeight.py
File metadata and controls
67 lines (59 loc) · 1.53 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class _Node:
__slots__ = '_element', '_left', '_right'
def __init__(self, element, left=None, right=None):
self._element = element
self._left = left
self._right = right
class BinaryTree:
def __init__(self):
self._root = None
def maketree(self, e, left, right):
self._root = _Node(e,left._root,right._root)
def inorder(self,troot):
if troot:
self.inorder(troot._left)
print(troot._element,end=' ')
self.inorder(troot._right)
def preorder(self,troot):
if troot:
print(troot._element,end=' ')
self.preorder(troot._left)
self.preorder(troot._right)
def postorder(self,troot):
if troot:
self.postorder(troot._left)
self.postorder(troot._right)
print(troot._element, end=' ')
def height(self,troot):
if troot:
x = self.height(troot._left)
y = self.height(troot._right)
if x > y:
return x + 1
else:
return y + 1
return 0
x = BinaryTree()
y = BinaryTree()
z = BinaryTree()
r = BinaryTree()
s = BinaryTree()
t = BinaryTree()
a = BinaryTree()
x.maketree(40,a,a)
y.maketree(60,a,a)
z.maketree(20,x,a)
r.maketree(50,a,y)
s.maketree(30,r,a)
t.maketree(10,z,s)
print('Inorder Traversal')
t.inorder(t._root)
print()
print('Preorder Traversal')
t.preorder(t._root)
print()
print('Postorder Traversal')
t.postorder(t._root)
print('Height')
print(t.height(t._root)-1)
print()