logo CodeStepByStep logo

evenBranches

Language/Type: Java binary trees

Write a method named evenBranches that returns the number of branch nodes in a binary tree that contain even numbers. Your method accepts as its parameter a TreeNode that refers to the root of the tree. A branch node is one that has one or two children (i.e., not a leaf node). For example, if a variable tree stores a reference to the root of the following tree:

(2 (8 (0)) (1 (7 (4)) (6 / (9))))

Then the call of evenBranches(tree) should return 3 because there are three branch nodes with even values (2, 8, and 6). Notice that the leaf nodes with even values are not included (the nodes storing 0 and 4).

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.