Problem Description
Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values (i.e., from left to right, level by level from leaf to root).
Key Insights
- Use a breadth-first search (BFS) to traverse the tree level by level.
- Utilize a queue to manage nodes during the traversal.
- Collect the values of nodes for each level into a temporary list.
- To achieve bottom-up order, either insert each level's list at the beginning of the result list or reverse the final list after a standard level order traversal.
Space and Time Complexity
Time Complexity: O(n) — Each node is visited exactly once. Space Complexity: O(n) — The space is used by the queue and the output list, where n is the number of nodes.
Solution
We adopt a BFS strategy using a queue. Starting from the root, we visit each node level by level. For each level, we collect the values into a temporary list. We then insert this list at the beginning of the result list, ensuring that lower levels appear before higher ones. This method efficiently handles the problem while meeting the required bottom-up order without needing additional reversal operations.