root = new TreeNode(N);
constructTree(N, root);
private void constructTree(int N, TreeNode node) {
if (N > 0) {
node.setLeft(new TreeNode(N-1));
constructTree(N-1, node.getLeft());
}
if (N > 1) {
node.setMiddle(new TreeNode(N-2));
constructTree(N-2, node.getMiddle());
}
if (N > 2) {
node.setRight(new TreeNode(N-3));
constructTree(N-3, node.getRight());
}
假设N是根数,三个将创建N-1,N-2,N-3的左中右节点。
EX:
5
/ | \
4 3 2
/|\
3 2 1
等
我的TreeNode类有以下变量:
private int number;
private TreeNode left, middle, right;
每当我构造一个大于28的整数树时,我都会得到一个OutOfMemoryError。我的递归方法是非常低效还是这很自然?谢谢!
答案 0 :(得分:2)
理论上,深度为N的完整三元树将具有(3^(N+1) - 1) / 2
个节点。如果N是28,则表示34,315,188,682,441个节点。如果每个节点以某种方式仅占用1个字节,那仍然是31.2太字节的RAM。在此之前,你的内存已经耗尽。
编辑:但是,您的代码似乎不会生成完整的树。当我运行以下程序来计算新节点的数量时:
static long nodes = 0;
static void constructTree(int N) {
if (N > 0) {
++nodes;
constructTree(N-1);
}
if (N > 1) {
++nodes;
constructTree(N-2);
}
if (N > 2) {
++nodes;
constructTree(N-3);
}
}
public static final void main (String[] args) throws Exception {
nodes = 1;
constructTree(28);
System.out.println(nodes);
}
假设您的TreeNode
构造函数没有创建新节点,它表明您在N = 28时创建了34,850,335个新节点,在N = 29时创建了64,099,760个新节点。鉴于你暗示N = 28成功,这更有意义。由于您没有显示TreeNode
,我们无法确切知道它将使用多少内存,但这些数字与典型的JVM内存限制在同一数量级内。您可以稍微增加最大JVM内存以挤出一两个级别。
但是,您可能希望仔细考虑为什么要生成此树并尝试使用不同的算法来执行您正在执行的操作。