I have been thinking lately and have come up with two options for finding the inorder traversal of a 2-3-4 tree. One of them is recursive approach with a switch case on the type of node it is and the other is more of an iterative approach. For background, the goal of this traversal is to produce the following set of elements from the tree above that.
[S]
/ \
[J O] [U]
/ | \ / \
[EH] [MN] [PQR] [T] [VWX]
{ {E} {H} {J} {M} {N} {O} {P} {Q} {R} {S} {T} {U} {V} {W} {Z} }
Since there can only be 2 3 or 4 children on a node I had the idea that either of the following approaches would work (pseudo-code).
The first way is to recurse from the root left, middle-left, middle-right, right, when necessary depending on the current size of the node:
list = new list
234InOrder(Node cur):
switch(cur.numElems)
case 1: // 2-node
234InOrder(cur.child[0])
list.add(cur.child[0])
234InOrder(cur.child[1])
break;
case 2: // 3-node
234InOrder(cur.child[0])
list.add(cur.child[0])
234InOrder(cur.child[1])
list.add(cur.child[1])
234InOrder(cur.child[2])
break;
case 3: // 4-node
234InOrder(cur.child[0])
list.add(cur.child[0])
234InOrder(cur.child[1])
list.add(cur.child[1])
234InOrder(cur.child[2])
list.add(cur.child[2])
234InOrder(cur.child[3])
break;
Or iteratively go to the far left node, "get" every element from that node, go back to the parent, proceed to the next child, repeat the process. Once all children have been seen, go to parent/root and repeat the process starting from the inorder successor of the root (sorry no pseudo code).
Which of these methods would be better for getting the desired set of elements within the tree?