1

I am trying to create a Java applet that animates a BTree. I have code to create the tree but now I am trying to display it. I thought the easiest way would be to print by level but I can't figure out how. The below code is the constructor for my nodes. Also, if anyone has a better suggestion for displaying my tree I would appreciate it.

    /***********************************************************************
 * Class BTNode
 * The BTNode is nothing else than a Node in the BTree. This nodes can be
 * greater or smaller it depends on the users order.
 **/

class BTNode {
    int order=0;
    int nKey=0;         // number of keys stored in node
    KeyNode kArray[];       // array where keys are stored
    BTNode btnArray[];  // array where references to the next BTNodes is stored
    boolean isLeaf;     // is the btnode a leaf
    BTNode parent;      // link to the parent node

    /**
       * BTNode(int order, BTNode parent);
       * Constructor, creats a empty node with the given order and parent
       **/
    BTNode(int order, BTNode parent) {
        this.order = order;
        this.parent = parent;
        kArray = new KeyNode[2 * order - 1];
        btnArray = new BTNode[2 * order];
        isLeaf = true;
    }
kfeeney
  • 919
  • 1
  • 8
  • 13

2 Answers2

3

You want to perform a level-order traversal of the tree. If space is not a limiting factor, I'd suggest building a queue of nodes that you wish to visit next (adding their child nodes onto the end of the queue upon visit).

eggyal
  • 122,705
  • 18
  • 212
  • 237
  • 1
    Thanks for the idea. I ended up using two queues (adding all the children of the nodes in the first queue to the second queue and then vice versa) this way I could keep track of when a line break was needed. – kfeeney May 05 '11 at 06:15
1

I would also recommend a level order transversal. Here is some sudocode for it:

Add root to queue
while queue is not empty
{
    r = queue.top()
    process r
    remove r from queue
    add r's non-NULL children to the queue
}
matzahboy
  • 3,004
  • 20
  • 25