Reputation: 971
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
Reputation: 441
assume the binary expression tree and how the inorder, preorder and postorder traversals act on it:
inorder
: left subtree, current root, right subtreepreorder
: current root, left subtree, right subtreepostorder
: left subtree, right subtree, current rootnow 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);
then right subtree:
postorder(preorder, prestart+i-inostart+1, inorder, i+1, length-i+inostart-1);
and then output our current root:
cout<<preorder[prestart]<<" ";
doing so recursively would result in postorder traversal of the tree.
Upvotes: 3