Tree traversal refers to visiting all the nodes of a tree exactly once. Visiting means doing something to the node. It can be as basic as printing the node.
Post-order traversal is one of the multiple methods to traverse a tree. It is mainly used for tree deletion.
The following algorithm is specific to a binary tree but can be generalized to an n-ary tree (a tree where each node can have at most n children nodes).
Postorder traversal is defined as a type of tree traversal which follows the Left-Right-Root policy such that for each node:
The algorithm for postorder traversal is shown as follows:
Consider the following tree:
If we perform a postorder traversal in this binary tree, then the traversal will be as follows:
Step 1: The traversal will go from 1 to its left subtree i.e., 2, then from 2 to its left subtree root, i.e., 4. Now 4 has no subtree, so it will be visited.
Suggested reading:
Hardware
What is profiling steel?
Optimal Pressure for Torch Cutting: A Comprehensive GuideStep 2: As the left subtree of 2 is visited completely, now it will traverse the right subtree of 2 i.e., it will move to 5. As there is no subtree of 5, it will be visited.
Step 3: Now both the left and right subtrees of node 2 are visited. So now visit node 2 itself.
Step 4: As the left subtree of node 1 is traversed, it will now move to the right subtree root, i.e., 3. Node 3 does not have any left subtree, so it will traverse the right subtree i.e., 6. Node 6 has no subtree and so it is visited.
Step 5: All the subtrees of node 3 are traversed. So now node 3 is visited.
Step 6: As all the subtrees of node 1 are traversed, now it is time for node 1 to be visited and the traversal ends after that as the whole tree is traversed.
So the order of traversal of nodes is 4 -> 5 -> 2 -> 6 -> 3 -> 1.
Comments
Please Join Us to post.
0