In: Computer Science
import java.util.Stack;
import java.util.ArrayList;
import java.util.Scanner;
class TreeNode{
int data;
ArrayList<TreeNode> children = new ArrayList<>();
TreeNode parent = null;
public TreeNode(int d){
data = d;
}
public TreeNode addChild(int d){
TreeNode n = new TreeNode(d);
n.setParent(this);
children.add(n);
return n;
}
public ArrayList<TreeNode> getChildren(){
return children;
}
public void setParent(TreeNode p){
parent = p;
}
public TreeNode getParent(){
return parent;
}
}
class Main {
public static void main(String[] args)
{
Scanner scan = new
Scanner(System.in);
int num;
//Create a tree
TreeNode root = new
TreeNode(scan.nextInt());
TreeNode node1 = root.addChild(scan.nextInt());
TreeNode node11 = node1.addChild(scan.nextInt());
TreeNode node12 = node1.addChild(scan.nextInt());
TreeNode node2 = root.addChild(scan.nextInt());
TreeNode node21 = node2.addChild(scan.nextInt());
TreeNode node22 = node2.addChild(scan.nextInt());
TreeNode node211 =
node21.addChild(scan.nextInt());
int newK = scan.nextInt();
System.out.println(""+largerK(root,
newK));
}
public static int largerK(TreeNode n, int k) {
//TODO: Find the number of elements
greater than k in the tree rooted in n
//Example: if the elements in the
tree are: 10, 20, 30, 40, 50, and k=25, the method should return:
3
}
}
Here is the answer for your problem.
I implemented a recursive solution I hope you are able to understand this as it is a well commented code.
Request : If you understand this do give it a like, if no then comment I will resolve your issue
JAVA CODE:
public static int largerK(TreeNode n, int k) {
//if the node is null then return the 0 as it will not have any child so no one can be greater than k
if(n == null)
return 0;
//initializing a count variable to count the number of elements greater than k
int count = 0;
//getting the children list of the current treenode
ArrayList<TreeNode> child = n.getChildren();
// iterating over each children of the TreeNode
for(int i = 0;i<child.size();i++){
//if the child's data is greater than k then increament the counter variable by 1
if(child.get(i).data>k)
count++;
// recursively call the largerK function for the child of the treenode and add the result of the sub problem to the main problem.
count += largerK(child.get(i),k);
}
// then return the count to the current TreeNode.
return count;
}
}
I am attaching screenshots of the code as well as output to help you understand better.
Source Code :
Console Output:
Here 10 20 30 40 50 are the nodes of the tree and 25 is the value of K.
So, this was the solution for the given
problem.
I hope, it will be helpful.
Do comment if you need more and if you are able to understand then
do give a thumbs up.
It really helps :)