0

如何在 C# 中从给定的 In Order 和 Pre-order 中获取 post order?

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.

这个按顺序和预购我从文本框中得到它,当按下其他文本框中的按钮时,我想显示发布订单结果。

我已经用 C++ 解决了,但是 PostOrder 函数有 C# 问题。

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] << " ";
}
4

1 回答 1

0

尝试这个

        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() + " ");
         }
于 2016-12-17T15:45:25.153 回答