Leetcode 145. Binary Tree Postorder Traversal
Given the root
of a binary tree, return the postorder traversal of its nodes’ values. Postorder traversal is a type of depth-first traversal where the nodes are recursively visited in this order: left subtree, right subtree, root.
For example, given a binary tree:
1
\
2
/
3
You should return the list [3, 2, 1]
.
root
is nullptr
)?
To solve this, we can use a recursive approach to traverse the tree in postorder. A postorder traversal visits nodes in the order:
For each node, we will:
Here’s how you can implement the postorder traversal recursively in C++:
#include <vector>
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr, right(nullptr) {}
TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};
class Solution {
public:
std::vector<int> postorderTraversal(TreeNode* root) {
std::vector<int> result;
postorderHelper(root, result);
return result;
}
private:
void postorderHelper(TreeNode* node, std::vector<int>& result) {
// Base case: if the node is null, just return.
if (node == nullptr) return;
// Recursive case: visit left subtree first.
postorderHelper(node->left, result);
// Then visit right subtree.
postorderHelper(node->right, result);
// Visit the node itself.
result.push_back(node->val);
}
};
This should cover all necessary aspects to solve the problem using a recursive approach. If you have further questions or need an iterative solution, feel free to ask!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?