Imagine you are building a file system explorer that needs to delete files and folders in the correct order, starting from the deepest files and moving up to the root folder. This requires visiting nodes in postorder.
Given the root of a binary tree, return the postorder traversal of its nodes' values. Postorder traversal visits the left subtree, then the right subtree, and finally the node itself.
The number of nodes in the tree is in the range [1, 10^5].-10^9 <= Node.val <= 10^9
Edge cases: Single node tree → output is the node itselfTree with only left children → output is nodes from bottom to topTree with only right children → output is nodes from bottom to top
def postorderTraversal(root: Optional[TreeNode]) -> List[int]:public List<Integer> postorderTraversal(TreeNode root)vector<int> postorderTraversal(TreeNode* root)function postorderTraversal(root)
def postorderTraversal(root: Optional[TreeNode]) -> List[int]:
# Write your solution here
pass
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
// Write your solution here
return new ArrayList<>();
}
}
#include <vector>
using namespace std;
vector<int> postorderTraversal(TreeNode* root) {
// Write your solution here
return {};
}
function postorderTraversal(root) {
// Write your solution here
}
Common Bugs to Avoid
Wrong: [1, 3, 2]Preorder traversal output instead of postorder; node appended before children.✅ Append node value after recursive calls to left and right children, not before.
Wrong: [2, 1]Missing left subtree nodes in traversal due to incorrect recursion or iteration.✅ Ensure recursion or iteration visits left child before appending node.
Wrong: []Returning empty list for non-empty tree due to missing base case or incorrect recursion.✅ Add base case to append node value when node is not null and has no children.
Wrong: Runtime error or crashNull pointer dereference due to missing null checks in recursion or iteration.✅ Check if node is null before accessing its children or value.
Wrong: Timeout or TLEInefficient traversal with repeated visits or exponential complexity.✅ Implement O(n) traversal visiting each node once using recursion or iterative stack.