forked from Lancelot03/Code-the-Problem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinMaxinBinaryTree.py
134 lines (70 loc) · 2.14 KB
/
MinMaxinBinaryTree.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
from sys import stdin, setrecursionlimit
import queue
setrecursionlimit(10 ** 6)
#Following is the structure used to represent the Binary Tree Node
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
#Representation of the Pair Class
class Pair :
def __init__(self, minimum, maximum) :
self.minimum = minimum
self.maximum = maximum
def getMinAndMax(root,p) :
#Your code goes here
if root == None:
return
p.minimum = min(p.minimum, root.data)
p.maximum = max(p.maximum, root.data)
getMinAndMax(root.left, p)
getMinAndMax(root.right, p)
return p
#Taking level-order input using fast I/O method
def takeInput():
levelOrder = list(map(int, stdin.readline().strip().split(" ")))
start = 0
length = len(levelOrder)
if length == 1 :
return None
root = BinaryTreeNode(levelOrder[start])
start += 1
q = queue.Queue()
q.put(root)
while not q.empty():
currentNode = q.get()
leftChild = levelOrder[start]
start += 1
if leftChild != -1:
leftNode = BinaryTreeNode(leftChild)
currentNode.left =leftNode
q.put(leftNode)
rightChild = levelOrder[start]
start += 1
if rightChild != -1:
rightNode = BinaryTreeNode(rightChild)
currentNode.right =rightNode
q.put(rightNode)
return root
def printLevelWise(root):
if root is None:
return
inputQ = queue.Queue()
outputQ = queue.Queue()
inputQ.put(root)
while not inputQ.empty():
while not inputQ.empty():
curr = inputQ.get()
print(curr.data, end=' ')
if curr.left!=None:
outputQ.put(curr.left)
if curr.right!=None:
outputQ.put(curr.right)
print()
inputQ, outputQ = outputQ, inputQ
# Main
root = takeInput()
p = Pair(float('inf'), float('-inf'))
pair = getMinAndMax(root,p)
print(str(str(pair.minimum) + " " + str(pair.maximum)))