i haven't really changed much, just rearranged things and given the Tree a decent constructor. i'm also using the return value from createTree which, i think, was the thing that was wrong with the original.
i get 85 nodes with img = 8 which is
1 level 0 node (size 8)
4 level 1 nodes (size 4)
16 level 2 nodes (size 2)
64 level 3 nodes (size 1)
which looks about right. have also added a level member to the tree but only use it to indent the output.
Code:
Tree tree;
//PImage img;
int img = 8;
int count = 0;
void setup() {
size(100,100);
noLoop();
//img = loadImage("monalisa.bmp"); // load image with 4x4 size
//loadPixels();
tree = createTree();
tree.display();
println("Count: " + count);
}
void draw() {
}
// create initial node
Tree createTree() {
Tree t = createNode(null, 0, 0, 0);
return t;
}
// create nodes (recursively)
Tree createNode(Tree parent, int x, int y, int level) {
//println("createNode x[" + x + "] y[" + y + "] level[" + level + "]");
Tree node = new Tree(parent, x, y, level);
// add child nodes (if size > 1)
int s = img >> level;
if (s > 1) {
s = img >> (level + 1);
node.child[0] = createNode(node, x, y, level + 1);
node.child[1] = createNode(node, x + s, y, level + 1);
node.child[2] = createNode(node, x, y + s, level + 1);
node.child[3] = createNode(node, x + s, y + s, level + 1);
}
return node;
}
// Tree Class
class Tree {
public int x,y;
public int value, cost, level;
public int size;
public Tree[] child = new Tree[4];
public Tree parent = null;
public boolean show = true;
public Tree() {
this(null, 0, 0, 0);
}
public Tree(Tree parent, int x, int y, int level) {
//println("New x[" + x + "] y[" + y + "] level[" + level + "]");
this.parent = parent;
this.x = x;
this.y = y;
this.level = level;
this.size = img >> level;
this.value = count; // NB global count
count++;
}
public void display() {
String padding = " ";
print(padding.substring(1, (this.level * 2) + 1));
println("Node[" + this.value + "]: x[" + this.x + "] y[" + this.y + "] size[" + this.size + "]");
if (child[0] != null && child[0].show == true) {
child[0].display();
}
if (child[1] != null && child[1].show == true) {
child[1].display();
}
if (child[2] != null && child[2].show == true) {
child[2].display();
}
if (child[3] != null && child[3].show == true) {
child[3].display();
}
}
}