Skip to content

Commit d9296b0

Browse files
authored
Create Binary Trees2-Minimum and Maximum in the Binary Tree
1 parent ae0cdbf commit d9296b0

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
For a given a Binary Tree of type integer, find and return the minimum and the maximum data values.
2+
Return the output as an object of Pair class, which is already created.
3+
Note:
4+
All the node data will be unique and hence there will always exist a minimum and maximum node data.
5+
Input Format:
6+
The first and the only line of input will contain the node data, all separated by a single space. Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of the node data.
7+
Output Format:
8+
The only line of output prints two integers denoting the minimum and the maximum data values respectively. A single line will separate them both.
9+
Constraints:
10+
2 <= N <= 10^5
11+
Where N is the total number of nodes in the binary tree.
12+
13+
Time Limit: 1 sec
14+
Sample Input 1:
15+
8 3 10 1 6 -1 14 -1 -1 4 7 13 -1 -1 -1 -1 -1 -1 -1
16+
Sample Output 1:
17+
1 14
18+
Sample Input 2:
19+
10 20 60 -1 -1 3 50 -1 -1 -1 -1
20+
Sample Output 2:
21+
3 60
22+
23+
******************************************Solution**********************************************
24+
private static Pair<Integer,Integer> maxMin=new Pair<Integer,Integer>(Integer.MAX_VALUE, Integer.MIN_VALUE);
25+
26+
public static Pair<Integer, Integer> getMinAndMax(BinaryTreeNode<Integer> root) {
27+
28+
getMinAndMaxHelper(root);
29+
return maxMin;
30+
}
31+
32+
private static void getMinAndMaxHelper(BinaryTreeNode<Integer> root)
33+
{
34+
if(root==null)
35+
return;
36+
int rootData=root.data;
37+
int maxVal=maxMin.maximum;
38+
if(rootData>maxVal)
39+
{
40+
maxMin.maximum=root.data;
41+
}
42+
int minVal= maxMin.minimum;
43+
if(rootData<minVal)
44+
{
45+
maxMin.minimum=root.data;
46+
}
47+
getMinAndMax(root.left);
48+
getMinAndMax(root.right);
49+
}

0 commit comments

Comments
 (0)