Question

Write a public method in java called average that finds the average of all values in...

Write a public method in java called average that finds the average of all values in a Binary Search Tree. You may assume items are always integer.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for this problem based on the limited info provided. Assumptions are included in comments. Comprehensive comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

/**

* method to calculate the average of all values in a BST. Assuming there is

* a variable called root that denotes the root node of the binary search

* tree. And assuming that Node class has a data field (int) and left and

* right Node pointers (Node type). this method uses two helper methods to

* assist the process, those are attached below.

*

* @return the average value.

*/

public double average() {

      // finding sum of all values

      double total = sum(root);

      // finding count of nodes

      double count_nodes = count(root);

      // dividing sum by count to get average, assuming BST is not empty

      double avg = (double) total / count_nodes;

      return avg;

}

// helper method to find the sum of all nodes, recursively

private double sum(Node n) {

      // if n is null, returning 0 (base case)

      if (n == null) {

            return 0;

      }

      // adding data of node n with sum values of left and righ subtrees and

      // returning this value.

      return n.data + sum(n.left) + sum(n.right);

}

// helper method to find the number of nodes, recursively

private int count(Node n) {

      if (n == null) {

            // base case

            return 0;

      }

      // finding number of nodes on left and right, adding 1 to it and

      // returning it

      return 1 + count(n.left) + count(n.right);

}

Add a comment
Know the answer?
Add Answer to:
Write a public method in java called average that finds the average of all values in...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT