OutOfMemoryError creating a tree recursively?
- by Alexander Khaos Greenstein
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!