logo Practice-It logo

BJP5 Exercise 17.21: matches

Language/Type: Java binary trees implementing IntTree
Related Links:
Author: Marty Stepp (on 2019/09/19)

Write a method matches that returns a count of the number of nodes in one tree that match nodes in another tree. A match is defined as a pair of nodes that are in the same position in the two trees relative to their overall root and that store the same data. Consider, for example, the following trees:

          tree1
          +---+
          | 3 |
          +---+
         /     \
     +---+     +---+
     | 4 |     | 7 |
     +---+     +---+
    /     \         \
+---+     +---+     +---+
| 0 |     | 9 |     | 2 |
+---+     +---+     +---+
               \
               +---+
               | 8 |
               +---+
        
          tree2
          +---+
          | 3 |
          +---+
         /     \
     +---+     +---+
     | 6 |     | 7 |
     +---+     +---+
    /         /     \
+---+     +---+     +---+
| 0 |     | 9 |     | 2 |
+---+     +---+     +---+
     \
    +---+
    | 8 |
    +---+
        

The overall root of the two trees match (both are 3). The nodes at the top of the left subtrees of the overall root do not match (one is 4 and one is 6). The top of the right subtrees of the overall root match (both are 7). The next level of the tree has 2 matches for the nodes storing 0 and 2 (there are two nodes that each store 9 at this level, but they are in different positions relative to the overall root of the tree). The nodes at the lowest level both store 8, but they aren't a match because they are in different positions. Therefore, these two trees have a total of 4 matches. Therefore the calls of tree1.matches(tree2) and tree2.matches(tree1) would each return 4.

public class IntTree {
    private IntTreeNode overallRoot;
    ...
}
Type your solution here:


This is a partial class problem. Submit code that will become part of an existing Java class as described. You do not need to write the complete class, just the portion described in the problem.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.