Hey Folks,
I have a tree and using proper fields and variables, I want to calculate total traveling time of a tree.
Here is my code:
private double time = 0;
..............
..............
..............
public static double time(TreeNode<City> tree{
City A = tree.getCity();
if (tree.hasLeftChild()){
time += tree.getLeftChild().getCity().distance(A);
time(tree.getLeftChild());
}
if (tree.hasNextSibling()){
time += tree.getNextSibling().getCity().distance(A);
time(tree.getNextSibling());
}
return time;
}
I want to calculate the total time of travelling a tree. Yet, there is one big issue: the field named time has to be static so that I can use it in my static methods. However, when it is static, the program always return 0. How should I make a change to calculate total traveling time of a tree???
Cheers.
Without going into the details of variable attributes, I will simply note that you wrote a recursive function which is returning a variable. I suggest you actually use that return and do whatever is necessary to assign the value at the end. Something like
Then when you call it;
The printf at the end is just to help figure out if there is some kind of attribute assignment problem vs bug in the function vs something else.
Code should try to avoid updating variables outside the scope of the code when possible. Makes for better safety in case of conversion to threading, signal handling, debugging, and generally prevents spooky action at a distance.
I’ll note in your sample code that you are apparently missing a close-parent in the function definition.