-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathFindMax_BT.py
68 lines (60 loc) · 1.42 KB
/
FindMax_BT.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
import queue
'''class for node of binary tree'''
class Node(object):
"""docstring for Node"""
def __init__(self, val=None):
super(Node, self).__init__()
self.left = None
self.right = None
self.val = val
'''class for binary tree'''
class BinaryTree(object):
"""docstring for BinaryTree"""
def __init__(self):
super(BinaryTree, self).__init__()
self.root = None
'''Insert node level wise'''
def insert(self, val):
new_node = Node(val)
if self.root is None:
self.root = new_node
return
Q = queue.Queue(maxsize=20)
Q.put(self.root) #Enqueue
while(Q.empty() is not True):
temp = Q.get() #Dequeue
if temp.left:
Q.put(temp.left)
else:
temp.left = new_node
Q.queue.clear()
return
if temp.right:
Q.put(temp.right)
else:
temp.right = new_node
Q.queue.clear()
return
Q.queue.clear()
'''Find max elem in binary tree using recurssion'''
def findMax(self, root):
maxval = -float('inf')
if root:
left = self.findMax(root.left)
right = self.findMax(root.right)
if left > right :
maxval = left
else:
maxval = right
if root.val > maxval:
maxval = root.val
return maxval
if __name__ == '__main__':
btree = BinaryTree()
btree.root = Node(1)
btree.root.left =Node(2)
btree.root.right = Node(3)
btree.insert(4)
btree.insert(5)
btree.insert(6)
print(btree.findMax(btree.root))