The code calls postorder on right subtree first, then left subtree, which reverses the correct order.
Step 2: Understand correct postorder order
Postorder requires left subtree first, then right subtree, then root visit.
Final Answer:
Left and right subtree calls are swapped -> Option A
Quick Check:
Left before right in postorder [OK]
Hint: Left subtree call must come before right [OK]
Common Mistakes:
Swapping left and right subtree calls
Visiting root before children
Omitting base case check
5. You want to collect all node values of a binary tree in postorder traversal into a vector. Which code snippet correctly implements this in C++?
hard
A. void postorder(Node* root, vector<int>& res) { if (!root) return; res.push_back(root->val); postorder(root->left, res); postorder(root->right, res); }
B. void postorder(Node* root, vector<int>& res) { if (!root) return; postorder(root->left, res); postorder(root->right, res); res.push_back(root->val); }
C. void postorder(Node* root, vector<int>& res) { if (!root) return; postorder(root->right, res); postorder(root->left, res); res.push_back(root->val); }
D. void postorder(Node* root, vector<int>& res) { if (!root) return; postorder(root->left, res); res.push_back(root->val); postorder(root->right, res); }
Solution
Step 1: Confirm traversal order in code
void postorder(Node* root, vector<int>& res) { if (!root) return; postorder(root->left, res); postorder(root->right, res); res.push_back(root->val); } calls postorder on left, then right subtree, then adds root value to vector, matching postorder.
Step 2: Check other options for order mistakes
The other options either add the root value too early or swap left and right calls, breaking postorder.
Final Answer:
void postorder(Node* root, vector<int>& res) { if (!root) return; postorder(root->left, res); postorder(root->right, res); res.push_back(root->val); } -> Option B