Binary Tree Postorder Traversal Given the root
of a binary tree, return the postorder traversal of its nodes’ values.
Example 1:


Input: root = [1,null,2,3] Output: [3,2,1]
Example 2:
Input: root = [] Output: []
Example 3:
Input: root = [1] Output: [1]
Constraints:
- The number of the nodes in the tree is in the range
[0, 100]
. -100 <= Node.val <= 100
Binary Tree Postorder Traversal Solutions
✅Time: O(n)
✅Space: O(h)
C++
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ans;
postorder(root, ans);
return ans;
}
private:
void postorder(TreeNode* root, vector<int>& ans) {
if (!root)
return;
postorder(root->left, ans);
postorder(root->right, ans);
ans.push_back(root->val);
}
};
Java
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
postorder(root, ans);
return ans;
}
private void postorder(TreeNode root, List<Integer> ans) {
if (root == null)
return;
postorder(root.left, ans);
postorder(root.right, ans);
ans.add(root.val);
}
}
Python
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans = []
def postorder(root: Optional[TreeNode]) -> None:
if not root:
return
postorder(root.left)
postorder(root.right)
ans.append(root.val)
postorder(root)
return ans
Watch Tutorial
Checkout more Solutions here