Post-order Traversal
Post-order traversal follows the "left, right, root" order. For each node, the algorithm recursively traverses the left subtree, then recursively traverses the right subtree, and finally processes the node itself. This traversal method is commonly used to delete a tree, as it ensures that a node's children are deleted before the node itself.
Post-Order Traversal (Tree)
Post-order Traversal Algorithm
Post-order traversal follows the "left, right, root" order. This means for each node, the algorithm recursively traverses the left subtree, then the right subtree, and finally processes the node itself. It's commonly used to delete a tree, as a node can be deleted after its children are deleted.
Algorithm Steps (Recursive)
- Recursively call post-order traversal on the left child, if it exists.
- Recursively call post-order traversal on the right child, if it exists.
- Visit the current node (e.g., add its value to a list).
- The base case for the recursion is when a node is null.
Iterative Post-order Traversal
The iterative approach for post-order traversal is a bit more complex than pre-order and in-order. A common method uses two stacks.
Algorithm Steps (Two Stacks)
- Initialization: Create two stacks, `s1` and `s2`. Push the root node to `s1`.
- Loop: While `s1` is not empty, do the following:
- Pop a node from `s1` and push it to `s2`.
- Push the left child of the popped node to `s1`.
- Push the right child of the popped node to `s1`.
- Result: After the loop, pop all elements from `s2` and add them to the result list. The result will be in post-order.