OutOfMemoryError creating a tree recursively?

Posted by Alexander Khaos Greenstein on Stack Overflow See other posts from Stack Overflow or by Alexander Khaos Greenstein
Published on 2013-11-04T03:30:30Z Indexed on 2013/11/04 3:54 UTC
Read the original article Hit count: 123

Filed under:
|
|
 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());
    }

Assume N is the root number, and the three will create a left middle right node of N-1, N-2, N-3.

EX:

     5
   / | \
  4  3  2
 /|\
3 2 1

etc.

My GameNode class has the following variables:

private int number;
private GameNode left, middle, right;

Whenever I construct a tree with an integer greater than 28, I get a OutOfMemoryError. Is my recursive method just incredibly inefficient or is this natural? Thanks!

© Stack Overflow or respective owner

Related posts about java

Related posts about recursion