Assignment #8: Random Quadtree
Let me
throw you in cold water...
We did
not talk about trees yet, but you will have to program a tree data structure,
even a special one, a Quadtree. A Quadtree is a linked data structure of nodes,
where every node is linked to max. 4 child-nodes, see the image below.
The top
node is called the "root". As you see in the example, it has 4 nodes
as children, which are again roots of smaller quadtrees. These, again, have
max. 4 nodes as children, which are again roots of smaller children, which, again,
have max. 4 nodes as children, which are again roots of smaller children and so
on (do you feel some recursion here?).
Important
for a tree (any tree) is, that there are no cycles, i.e. each node, except for
the root, has exactly one parent, i.e. there is only a single node that
contains a link to it; the root has no parent. Usually, trees are implemented
such they only link downwards, i.e. each node contains references to the children,
not to the parent.
Your
task:
·
Create the a data structure that can represent a quadtree, i.e. create
the classes QNode and QuadTree. The QNodes should contain a double value.
·
In class QuadTree, create a method "insertAtRandomPosition(double
v)". This method should, from the root on, create a random position index
(between 0 and 3) POS and insert a new node (containing the value v) at POS if
the position is empty. If the position is not empty, it should go to the child
at POS, create a random position, check and insert if possible etc.
·
In class QuadTree, write a recursive method "sum()", that sums
up all values in this tree.
·
Test your structure with some code in a third class, class Main: instantiate
a QuadTree qt, and fill it with values 1,2,3,4,...,100 using the
insertAtRandomPosition() method. The call qt.sum(). You know it should return
5050 (that's the sum from 1...100 = 101*50 = 5050).
If that
is not enough, write a method that visualizes the tree as seen in the figure
above (recursion!), for 5 bonus points!
That's
it, good luck!