0

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?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Telo Springs
  • 45
  • 1
  • 12

1 Answers1

0

I would suggest a recursive solution because it is much easier to implement and to read. Also you could use a loop to get rid of the 3 cases.

Assuming your node datastructure is something like this:

class 234Node:
    keys: list of KeyType
    childs: list of Nodes
    # with 1 <= len(items) == len(childs) - 1 <= 3

that would be (in a pythonic notation):

def inorder_traversal(node, inorder):
    if not node:
        return

    inorder_traversal(node.childs[0])
    for i in range(len(node.keys)):
        inorder.append(node.keys[i])
        inorder_traversal(node.childs[i+1])

# and use
t = someTree
inorder = []
inorder_traversal(t.root, inorder)
Hannes
  • 1,118
  • 8
  • 15