树中所有节点的平均值中的 OutOfMemory 错误

OutOfMemory error in average value of all nodes in tree

public class Node {

  int value;
  List<Node> childNodes;

  Node(int x) {
      value = x;
      childNodes = new ArrayList<>();
  }
}

这是节点的定义。

 public static double averageNodes(Node root) {
      int numofnodes = 0;
      int sum = 0;
      Stack<Node> s = new Stack<Node>();
      s.add(root);
      while (!s.isEmpty()) {
          Node n = s.pop();
          numofnodes++;
          sum += n.value;
            for (Node temp : root.childNodes) {
              s.push(temp);  // Line 1
          }
      }
      return sum / numofnodes;
  }

我使用堆栈的深度优先搜索来遍历树。但是,当我在 eclipse 中单击 运行 时,第 1 行中会显示一条错误消息 "Exception in thread "main" java.lang.OutOfMemoryError: Java heap space"。任何人都知道修复代码以避免此错误?

您不能总是添加 root 节点的 children,而是添加 n 节点的

for (Node temp : n.childNodes) {
    s.push(temp);  // Line 1
}

您的代码会导致无限循环和无限增长的堆栈,因为您总是一遍又一遍地添加 root 节点的 children。

你取出一个元素,把所有 children 都放进去,取出,把它们全部放进去,等等。这只是一个小错误,但它造成的后果相当严重。