/* Tree structure: 1 / \ 2 3 / \ 4 5 */ void postorder(int* arr, int index, int size) { if (index >= size || arr[index] == -1) return; postorder(arr, 2*index + 1, size); // left postorder(arr, 2*index + 2, size); // right printf("%d ", arr[index]); } int main() { int tree[] = {1, 2, 3, 4, 5}; int size = sizeof(tree)/sizeof(tree[0]); postorder(tree, 0, size); return 0; }
Postorder traversal visits nodes in the order: left child, right child, then the node itself.
For the given tree, the traversal is: 4 (left of 2), 5 (right of 2), 2 (root of left subtree), 3 (right child of root), 1 (root).
void postorder(int* arr, int index, int size) { if (index >= size || arr[index] == -1) return; postorder(arr, 2*index + 1, size); postorder(arr, 2*index + 2, size); printf("%d ", arr[index]); } int main() { int tree[] = {10, 5, 15, -1, 7, -1, 20}; int size = sizeof(tree)/sizeof(tree[0]); postorder(tree, 0, size); return 0; }
Postorder visits left, then right, then root.
Left subtree of 10: nodes 5 and 7 (7 is right child of 5).
Right subtree of 10: nodes 15 and 20 (20 is right child of 15).
Traversal: 7 (left subtree right child), 5 (left subtree root), 20 (right subtree right child), 15 (right subtree root), 10 (root).
void postorder(int* arr, int index, int size) { if (arr[index] == -1) return; postorder(arr, 2*index + 1, size); postorder(arr, 2*index + 2, size); printf("%d ", arr[index]); } int main() { int tree[] = {1, 2, 3, 4, 5}; int size = sizeof(tree)/sizeof(tree[0]); postorder(tree, 0, size); return 0; }
The function checks arr[index] == -1 before verifying if index is within the array bounds.
If index is out of bounds, accessing arr[index] causes a runtime error.
Correct approach is to check index >= size before accessing arr[index].
Postorder traversal visits left subtree, then right subtree, then the root node last.
So the root is visited after all its children.
void postorder(int* arr, int index, int size) { if (index >= size || arr[index] == -1) return; postorder(arr, 2*index + 1, size); postorder(arr, 2*index + 2, size); printf("%d ", arr[index]); } int main() { int tree[] = {8, 3, 10, 1, 6, -1, 14, -1, -1, 4, 7, -1, -1, 13, -1}; int size = sizeof(tree)/sizeof(tree[0]); postorder(tree, 0, size); return 0; }
Traverse left subtree of 8: nodes 3, 1, 6, 4, 7.
Traverse right subtree of 8: nodes 10, 14, 13.
Postorder visits left subtree nodes first (1 4 7 6 3), then right subtree nodes (13 14 10), then root (8).
