简体   繁体   中英

Counting matching nodes on a tree

I am trying this problem on Practice-It, but have been having trouble with it for quite a while.

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.

So far, I've tried the following below, but I don't quite get the count I want, and I'm not quite sure why.

 public int matches(IntTree t2) { return match(overallRoot, t2.overallRoot); } public int match(IntTreeNode tree1, IntTreeNode tree2) { if(tree1 == null && tree2 == null) return 1; if(tree1 == null || tree2 == null) return 0; if(tree1.data == tree2.data) return 1; int left = match(tree1.left, tree2.left); int right = match(tree1.right, tree2.right); return left + right; }

Any help would really be appreciated!

You're stopping your search if the current node matches. If it's different, you check left and right, but on a match you return one.

You are very close to the solution, you have to consider:

  • if one of the nodes is null you can stop the visit for the subtrees and return 0
  • if the data for the two roots are different the count is 0 otherwise is 1 and after you can calculate the count for the two subtrees adding to the count for the two roots.

Below my suggestions as code:

public int match(IntTreeNode tree1, IntTreeNode tree2) {
    if(tree1 == null || tree2 == null) { return 0; }
    int count = tree1.data == tree2.data ? 1 : 0;
    int left = match(tree1.left, tree2.left);
    int right = match(tree1.right, tree2.right);
    return count + left + right; 
}

Full answer for the practice it one:

int matches(IntTree tree2) {
    return matches(tree2.overallRoot, this.overallRoot);
}
int matches(IntTreeNode tree1, IntTreeNode node2)
{
    int left=0, right=0, count =0;
    if(tree1 == null && this != null || this == null && tree1 != null) { return 0; }
     count = tree1.data == node2.data ? 1 : 0;
    if(tree1.left != null && node2.left !=null){
     left = matches(tree1.left, node2.left);}
    if(tree1.right != null && node2.right !=null){
     right = matches(tree1.right, node2.right);}
    return count + left + right;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM