递增问题在树上旅行-静态问题

问题描述

|| 嘿伙计, 我有一棵树,并使用适当的字段和变量,我想计算一棵树的总行驶时间。 这是我的代码
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;

}
我想计算走树的总时间。但是,有一个大问题:名为时间的字段必须是静态的,以便我可以在静态方法中使用它。但是,当它为静态时,程序始终返回0。我应该如何进行更改以计算树的总行驶时间? 干杯。     

解决方法

        在不涉及变量属性的细节的情况下,我将简单地注意到您编写了一个递归函数,该函数将返回一个变量。我建议您实际使用该返回值,并尽一切必要在末尾赋值。就像是
public static double time(TreeNode<City> tree{
    double thistime = 0.0;
    City A = tree.getCity();
    if (tree.hasLeftChild()){
        thistime += tree.getLeftChild().getCity().distance(A);
        thistime += time(tree.getLeftChild());
    }
    if (tree.hasNextSibling()){
        thistime += tree.getNextSibling().getCity().distance(A);
        thistime += time(tree.getNextSibling());
    }
    return thistime;
}
然后,当您调用它时;
time = time(root);
printf(\"Time is %f,actual time should be %f\\n\",time,time(root));
最后的printf只是用来帮助确定是否存在某种属性分配问题,函数中的错误或其他问题。 代码应尽可能避免在代码范围之外更新变量。在转换为线程,信号处理,调试的情况下,可以提供更好的安全性,并且通常可以防止远距离的怪异行为。 我将在示例代码中指出,您显然在函数定义中缺少近亲。