I was solving this question - Find PostOrder traversal from Inorder and Preorder traversals of a binary tree. On GeeksForGeeks, I saw the below solution for this:
// 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] + " ");
}
Now, I know that in postorder, we visits the node after traversing left and right subtrees and that's why, I could deduce from the comments in the printPostOrder() method that firstly something is done with left subtree, then right one and then the node's data is getting printed. I draw some initial recursive calls on paper and it's working fine but I just can't understand how can someone come up with this solution? I'm specially confused in the statement calling the printPostOrder for right subtree. Can anyone please help me to understand what's the logic here behind recursion and how I can understand it by visualizing it properly?