Class Diagnostic {
//Get the size in bytes of an object
static long sizeOf(Object object);
//Get the references for an object (leafs)
static List<Object> getRefs(Object object);
//Implement this with those above
public Long objectSize(Object object);
}
How would you implement objectSize to return the size in bytes of the object?
The method objectSize return the size in bytes of all children nodes combined (every node on the tree).
Example:
Object A (19 bytes)
/ \
/ \
B(20) C(37)
/
/
C(15)
Answer: 19+20+37+15 = 91
I had this question during an interview and I am very curious to see others answers. Since, I didn't know much about tree traversal algorithm.
I came up with this... (I know it's bad or not ;) , just trying to learn)
public Long objectSize(Object object) {
List<Object> objectList = new ArrayList<Object>();
Long sum = sizeOf(object);
objectList = getRefs(object);
for(Object object : objectList){
sum += objectSize(object);
}
return sum;
}
I noticed that I could have a cycle and run through a stackoverflow error, because I didn't check if I had already went trough a "node". Then I tough I should have another datastructure (like a hashmap for handling key/value) to handle temporary list for comparison.