logo CodeStepByStep logo

sum

Language/Type: Java binary trees

Write a method named sum that returns the sum of the data values stored in a binary tree. Your method accepts as its parameter a TreeNode that refers to the root of the tree. For example, the following tree has a sum of 33, so if a variable named tree refers to its root, the call of sum(tree) should return 33.

(3 (-9 (12) (24 (3 (0)) (-9 / (-6)))) (15 / (0)))

Assume that you are interacting with TreeNodes as defined below:

public class TreeNode {
    public int data;
    public TreeNode left;
    public TreeNode right;
    
    public TreeNode() { ... }
    public TreeNode(int data) { ... }
    public TreeNode(int data, TreeNode left, TreeNode right) { ... }
}
Method: Write a Java method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.