-5

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);
  }
}
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Vaibhav
  • 1
  • 3
  • You are printing the value of node twice. Also, if node is null then there should not be any else statement IMO. – Abhishek Bansal Oct 30 '13 at 06:34
  • Is degree=3 true for all nodes or 1<=degree<=3. You should check for existence of branches and then simply execute them. – user568109 Oct 30 '13 at 06:47
  • @user568109 i want to execute this only for three degree tree ... it works or have some problem attached with it..?? – Vaibhav Oct 30 '13 at 07:07

1 Answers1

0

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);
  }
}
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138