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.
I’m not a fan of these two parts:
For the first statement, why would the average of an empty tree be the highest possible Double? Seems arbitrary. It would be simpler to say it doesn’t exist,
Double.NaN, or even0.0– since the tree has zero elements in it.For the second statement, you have the logic correct in that if both the children are null, you get back its value. However, you’re going to be wrecking your average along the way – if you have twelve nodes, and you’re on your third, then your average values will be different when you move to your fourth node.
Move
nodeCountto a higher scope, and don’t worry about computing the actual average until you’ve counted the sum of all nodes from the recursive call. Lastly, pass along the total sum of your nodes as you go along.