Skip to content

Commit 167e6a5

Browse files
authored
Create Nodes Greater than X
1 parent a0f505a commit 167e6a5

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
For a given a binary tree of integers and an integer X, find and return the total number of nodes of the given binary tree which are having data greater than X.
3+
Input Format:
4+
The first line of input will contain the node data, all separated by a single space.
5+
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.
6+
The second line of input contains an integer, denoting the value of X.
7+
Note: You are not required to print anything explicitly. It has already been taken care of.
8+
9+
Output Format:
10+
The only line of output prints the total number of nodes where the node data is greater than X.
11+
Constraints:
12+
1 <= N <= 10^5
13+
Where N is the total number of nodes in the binary tree.
14+
Time Limit: 1 sec
15+
16+
Sample Input 1:
17+
1 4 2 3 -1 -1 -1
18+
2
19+
Sample Output 1:
20+
2
21+
Explanation for Sample Input 1:
22+
Out of the four nodes of the given binary tree, [3, 4] are the node data that are greater than X = 2.
23+
24+
Sample Input 2:
25+
5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1
26+
5
27+
Sample Output 2:
28+
3
29+
*/
30+
31+
/*
32+
33+
Following is the structure used to represent the Binary Tree Node
34+
35+
class BinaryTreeNode<T> {
36+
T data;
37+
BinaryTreeNode<T> left;
38+
BinaryTreeNode<T> right;
39+
40+
public BinaryTreeNode(T data) {
41+
this.data = data;
42+
this.left = null;
43+
this.right = null;
44+
}
45+
}
46+
47+
*/
48+
49+
public class Solution {
50+
51+
public static int countNodesGreaterThanX(BinaryTreeNode<Integer> root, int x) {
52+
//Your code goes here
53+
if (root==null)
54+
{
55+
return 0;
56+
}
57+
58+
int smallOutput=countNodesGreaterThanX(root.left,x)+countNodesGreaterThanX(root.right,x);
59+
if (root.data>x)
60+
{
61+
return smallOutput+1;
62+
}
63+
else
64+
{
65+
return smallOutput;
66+
}
67+
}
68+
69+
}

0 commit comments

Comments
 (0)