Answered! Imagine that you have a completely functioning tree that holds only integers (int). Write a method nPos() that you…

JAVA PLZ
(2) Tree Traversal Imagine that you have a completely functioning tree that holds only integers (int). write a method nPos0that you can add to your tree that returns the number of nodes in a binary search tree whose item field/payload is a positive integer (ie., greater than 0). For full credit You need to use recursion, and you also need to limit your search only to the parts of the tree that could contain positive values. (.e., dont search parts of the tree that are known to only contain non-positive numbers.) Assume that you are writing a public method for an IntTree class, using an IntTreeNode class. You may define private helper methods to solve this problem, but otherwise you may not call any other methods of the class.

Imagine that you have a completely functioning tree that holds only integers (int). Write a method nPos() that you can add to your tree that returns the number of nodes in a binary search tree whose item field/payload is a positive integer (i.e., greater than 0). For full credit, you need to use recursion, and you also need to limit your search only to the parts of the tree that could contain positive values. (i.e., don’t search parts of the tree that are known to only contain non-positive numbers.) Assume that you are writing a public method for an IntTree class, using an IntTreeNode class. You may define private helper methods to solve this problem, but otherwise you may not call any other methods of the class.

Expert Answer

 public class IntTree {

public static IntTreeNode root;
private int sortedValue=0;
public IntTree(){
this.root = null;
}

public void insert(int id){
IntTreeNode newNode = new IntTreeNode(id);
if(root==null){
root = newNode;
return;
}
IntTreeNode current = root;
IntTreeNode parent = null;
while(true){
parent = current;
if(id<current.data){
current = current.left;
if(current==null){
parent.left = newNode;
return;
}
}else{
current = current.right;
if(current==null){
parent.right = newNode;
return;
}
}
}
}
public int nPos(IntTreeNode root){
if(root!=null){
sortedValue=nPos(root.left);
if(root.data>0){
sortedValue=sortedValue+1;
}
sortedValue=nPos(root.right);
}
return sortedValue;
}
public static void main(String arg[]){
IntTree b = new IntTree();
b.insert(-3);b.insert(8);
b.insert(1);b.insert(4);b.insert(6);b.insert(2);b.insert(10);b.insert(9);
b.insert(20);b.insert(25);b.insert(-15);b.insert(-16);
System.out.println(b.nPos(root));
}
}

class IntTreeNode{
int data;
IntTreeNode left;
IntTreeNode right;
public IntTreeNode(int data){
this.data = data;
left = null;
right = null;
}
}

Still stressed from student homework?
Get quality assistance from academic writers!