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).
For an n-ary tree:
The following code snippet implements post-order traversal for a binary tree.
#include <iostream>using namespace std;struct Tree{char data;Tree *left;Tree *right;Tree(char data){this -> data = data;left = NULL;right = NULL;}};void PostOrderTraversal(Tree *node){if(node == NULL){return;}else{PostOrderTraversal(node -> left);PostOrderTraversal(node -> right);cout << node -> data << ", ";}}int main() {Tree *root = new Tree('a');root -> left = new Tree('b');root -> right = new Tree('c');root -> left -> left = new Tree('d');root -> left -> left -> left = new Tree('e');root -> left -> left -> right = new Tree('f');PostOrderTraversal(root);return 0;}
Free Resources