Bugaboo
Bugaboo

Reputation: 971

Generate the post-order traversal given the in-order and pre-order traversal

I see that the code is posted here: How do I output the preorder traversal of a tree given the inorder and postorder tranversal?

I have trouble understanding the logic though, especially, the recursion for the right part of the tree:

postorder(preorder, prestart+i-inostart+1, inorder, i+1, length-i+inostart-1);

Any help would be appreciated.

Upvotes: 0

Views: 2107

Answers (1)

Ehsan Shoja
Ehsan Shoja

Reputation: 441

assume the binary expression tree and how the inorder, preorder and postorder traversals act on it:

  1. inorder: left subtree, current root, right subtree
  2. preorder: current root, left subtree, right subtree
  3. postorder: left subtree, right subtree, current root

now the current code, first identifies the left and right subtrees. as we know the first element of preorder array is our root and we could find our corresponding root in inorder array. as we know all elements before root are left subtree's elements and all elements after it are right subtree's elements.

we want to produce postorder traversal so we recursively continue with left subtree:

   postorder(preorder, prestart+1, inorder, inostart, i-inostart);
  1. prestart+1: because the root of left subtree is just after the current root in preorder traversal
  2. i-inostart: because i is the index of our root in inorder array so i-inostart would be the size of left subtree

then right subtree:

   postorder(preorder, prestart+i-inostart+1, inorder, i+1, length-i+inostart-1);
  1. prestart+i-inostart+1: as I told above i-inostart is the size of left subtree and also we know that in preorder array the root of right subtree would come after the current root and the whole subtree so its index would be prestart+i-inostart+1
  2. i+1: because in inorder array the root's index was i and the element after that should be the start of right subtree in inorder array
  3. length-i+inostart-1: because the size of right subtree would be length minus the size of left subtree and minus 1 (the root)

and then output our current root:

   cout<<preorder[prestart]<<" ";

doing so recursively would result in postorder traversal of the tree.

Upvotes: 3

Related Questions