Question

I'm trying to write an algorithm for inorder traversal (left, node, mid, right) of a three degree tree.

Is the below a correct algorithm for this?

inorder(node)
{
  if (node) {
    inorder(node->left);
    print("%d", node->value);
    if (node->mid) {
      inorder(node->mid);
      print("%d", node->value);
      inorder(node->right);
    }
    else
      inorder(node->right);
  }
}
Was it helpful?

Solution

You're incorrectly printing the node's value twice.

You don't need to check node->mid, as this is checked inside inorder(node->mid);.

inorder(node)
{
  if (node)
  {
    inorder(node->left);
    print("%d ", node->value);
    inorder(node->mid);
    inorder(node->right);
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top