Search code examples
c#inorderpreorderpostorder

How to get postOrder from given InOrder and PreOrder in C#?


How to get post order from given In Order and Pre-order in C#?

In Order: 8,4,10,9,11,2,5,1,6,5,7.
Pre-order: 1,2,4,8,9,10,11,5,3,6,7.

This In Order and Pre-order I get it from texts boxes and when press button in other texts boxes I want to show Post Order Result.

I have already solved in C++,but i have C# problems with PostOrder function.

int search(int arr[], int x, int n)
{
   for (int i = 0; i < n; i++)
     if (arr[i] == x)
        return i;
   return -1;
}

// Prints postorder traversal from given inorder and preorder traversals
void printPostOrder(int in[], int pre[], int n)
{
   // The first element in pre[] is always root, search it
   // in in[] to find left and right subtrees
   int root = search(in, pre[0], n);

   // If left subtree is not empty, print left subtree
   if (root != 0)
      printPostOrder(in, pre+1, root);

   // If right subtree is not empty, print right subtree
   if (root != n-1)
      printPostOrder(in+root+1, pre+root+1, n-root-1);

   // Print root
   cout << pre[0] << " ";
}

Solution

  • try this

            int search(int[] arr, int x, int n)
            {
               for (int i = 0; i < n; i++)
                 if (arr[i] == x)
                    return i;
               return -1;
            }
    
            // Prints postorder traversal from given inorder and preorder traversals
             void printPostOrder(int[] _in, int[] pre, int n)
             {
               // The first element in pre[] is always root, search it
               // in in[] to find left and right subtrees
               int root = search(_in, pre[0], n);
    
               // If left subtree is not empty, print left subtree
               if (root != 0)
                  printPostOrder(_in, pre.Skip(1).ToArray(), root);
    
               // If right subtree is not empty, print right subtree
               if (root != n-1)
                  printPostOrder(_in.Skip(root+1).ToArray(), pre.Skip(root+1).ToArray(), n-root-1);
    
               // Print root
               Console.Write(pre[0].ToString() + " ");
             }