I have a Node class as follows:
public class Node {
private int value;
private Node leftNode;
private Node rightNode;
public Node(Node leftNode, Node rightNode, int value){
this.leftNode = leftNode;
this.rightNode = rightNode;
this.value = value;
}
//Getter and Setter methods for these variables are defined here
}
This Node class is used to create a Binary tree. I am writing a recursive function in JAVA to calculate the average of all the nodes. The code I have written below does not give correct answer. I think this is because the values of the parameters average and nodeCount are passed, and not the references.
public double treeAverage(Node node, double average, int nodeCount){
nodeCount ++;
if(node == null) return Double.MAX_VALUE;
if(node.getLeftNode()==null && node.getRightNode()==null){
average = ( average + node.getValue() )/nodeCount;
}
if(node.getLeftNode()!=null){
average = treeAverage(node.getLeftNode(), average, nodeCount);
}
if(node.getRightNode()!=null){
average = treeAverage(node.getRightNode(), average, nodeCount);
}
return average;
}
What would be a correct way to right this recursive function in Java? (in C I can pass the references to those parameters). Please correct me if I am wrong.