0

I don't know how to approach the algorithm. I was thinking something like that:

TreeNode n = root;
while(n.first.first!=0){ 
    n=n.first;
} // finding the leftMost parent
//printing the first child key, then first num of parent, then second child.. and so on
  

Does somebody have better idea?

Community
  • 1
  • 1
Blagch
  • 95
  • 8

1 Answers1

2

According to 2-3 tree definition, you could meet 3 types of nodes:

  • internal node with 2 children and 1 value
  • internal node with 3 children and 2 value
  • leaf with no children and 1 or 2 values

Having that information you could use a recursive method walking through nodes, starting from root node. If it meet leaf node it simply print values. In other cases the method have to call itself for the most left node (jump to left node), then print first value, then jump to next node and so one. After that the method is ending so the whole algorithm is ending (if actual node is a root node) or jump back to parent node (if actual node is an internal, children node)

Here is the pseudocode. I left the actual implementation for yourself. Study that and make sure you understand the method's flow (you could usue debugger and track the actual parameters)

/* you start algorithm by calling recursivePrint(root) */

void recursivePrint(node){

    if (node is a leaf){

        /* Here print node's value/values */

    } else if (node has 2 children){

        recursivePrint(node.leftChild);
        /* Here print node's value */
        recursivePrint(node.rightChild);

    } else if (node has 3 children)

        recursivePrint(node.leftChild);
        /* Here print node's left value */
        recursivePrint(node.middleChild);
        /* Here print node's right value */
        recursivePrint(node.rightChild)

    }

    /* Shouldn't be other cases in 2-3 trees */
}
Jakub Ch.
  • 3,577
  • 3
  • 24
  • 43
  • I got it, so what if I have a B-Tree of order 3, it should somehow go back to the parent too? – Blagch Sep 10 '16 at 14:10
  • What you mean? For general case of B-Tree the above code is not quite suitable, but changing it a little will work. The concept is simple: having a node r first process the subtree from c1 reference (call method recursively `recursivePrint(r.c1)`), then print value of k1, then process subtree from c2 reference, then print value of k2 and so on... till it has any next value or reference (naming convention from picture: [link](https://pl.wikipedia.org/wiki/B-drzewo#/media/File:B-tree-definition.png)) – Jakub Ch. Sep 10 '16 at 15:28