I know that In-order traversal(VISIT LEFT, VISIT ROOT, VISIT RIGHT) on a binary search tree gives me a sorted result. But I need to do a Post-order traversal (VISIT LEFT, VISIT RIGHT, VISIT ROOT) on a binary tree and the result should give me sorted values.
In order to achieve that, how should I construct my binary tree?
Post-order Traversal In this traversal method, the root node is visited last, hence the name. First we traverse the left subtree, then the right subtree and finally the root node.
It is not possible to construct a general Binary Tree from preorder and postorder traversals (See this). But if know that the Binary Tree is Full, we can construct the tree without ambiguity.
Since the root is visited last, it must contain the largest item. Since the left subtree is visited before the right subtree, all items in the left subtree must be smaller than any item in the right subtree.
So to construct a tree like this you can proceed as follows: If you insert an item which is greater than the root, that item becomes the new root. If you insert an item which is smaller than the root but greater than the root of the left subtree, insert it into the right subtree. Else insert it into the left subtree.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With