Seinfeld Seinfeld - 2 months ago 6
Java Question

How to cast in Java from type Node to Integer in Binary Tree?

I've kinda specific problem. I need to implement usual binary tree methods, but after I'm done with that I have to add "hits". More concretely, every time I find some Node (or just traverse it) that Node gets a hit. Example given:

Imagine normal Binary Tree with two parents and two children. Let's assume I have to find one of the two children. In order for me to do that, I have to traverse the root, then the parents before I can get to a children. Therefore, every of these Nodes that were traversed will get a hit. And it accumulates over the time. So obviously, root will always have most hits. I hope I made it easier to understand.

I implemented methods and it works just fine. Unfortunately, every time new Node is created, number of hits should be set to 0. That's where the problem comes.
I declared

int[] hitCounter = new int[]
and with the following code:

public class BinaryTree {
Node root;
int[] hitCounter = new int[1000];

public void add(int data) {

Node addingNote = new Node(data);

if (root == null) {
root = addingNote;
hitCounter[addingNode] = 0;
} else
addNode(root, addingNote);

}


I assumed that this would work, but obviously
hitCounter[addingNode] = 0;
does not work since
hitCounter
is Array type and
addingNode
is Node type. How should I resolve this problem ?

Answer

I think it would be easier if each node had its own hit count. Then every time that node is accessed you could call a function that increments the hit count by 1 (hitCountIncrement). You could also have a method on each node that resets hit count to 0 (hitCountReset). Finally, you could have a method in your BinaryTree class that traverses all nodes and calls the hitCountReset method on each one when needed.

Edit:

Example code

public class Node{

int hitCount = 0; //this should be set in the constructor

public void hitCountIncrement() {
    hitCount++;
}

public void hitCountReset() {
    hitCount = 0;
}
}

public class BinaryTree {

    public void resetAllCounts(){
    for(Node currNode:Nodes){
        currNode.hitCountReset();
    } 
}