我正在解决这个问题 - Find PostOrder traversal from Inorder and Preorder traversals of a binary tree。在 GeeksForGeeks 上,我看到了以下解决方案:
// A utility function to search x in arr[] of size n
static 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
static void printPostOrder(int in1[], 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(in1, pre[0], n);
// If left subtree is not empty, print left subtree
if (root != 0)
printPostOrder(in1, Arrays.copyOfRange(pre, 1, n), root);
// If right subtree is not empty, print right subtree
if (root != n - 1)
printPostOrder(Arrays.copyOfRange(in1, root+1, n), Arrays.copyOfRange(pre, 1+root, n), n - root - 1);
// Print root
System.out.print( pre[0] + " ");
}
现在,我知道在后序中,我们在遍历左右子树后访问该节点,这就是为什么,我可以从 printPostOrder() 方法中的注释推断出首先对左子树进行处理,然后是右子树,然后是节点的正在打印数据。我在纸上画了一些初始的递归调用,它工作正常,但我就是不明白有人怎么能想出这个解决方案?我在为右子树调用 printPostOrder 的语句中特别困惑。谁能帮我理解递归背后的逻辑是什么,以及如何通过正确地可视化它来理解它?