Binary Tree Level Order Traversal II
Given the root of a binary tree, perform a level order traversal, but return the result in a list of lists where the last level appears first, and the root level appears last. This is useful for understanding tree structures from the bottom up, which can be helpful in various tree manipulation algorithms.
Problem Description
You are tasked with implementing a function that takes the root of a binary tree as input and returns a 2D list (a list of lists) representing the level order traversal of the tree. However, the order of the levels in the output should be reversed. The list representing the last level of the tree should be the first element in the overall list, and the list representing the root level should be the last element.
Key Requirements:
- Traverse the tree level by level.
- Collect all nodes at each level into a separate list.
- Reverse the order of these level lists so that the last level comes first.
- Handle empty trees correctly.
Expected Behavior:
The function should return a list of lists of integers. Each inner list represents a level of the tree, containing the values of the nodes at that level, ordered from left to right. The outer list should contain these inner lists in reverse level order.
Edge Cases:
- An empty tree (root is null).
- A tree with only one node.
- A skewed tree (e.g., a linked list).
Examples
Example 1:
Input: root = [3,9,20,null,null,15,7]
Visual Representation of the tree:
3
/
9 20
/
15 7
Output: [[15,7],[9,20],[3]]
Explanation:
- Level 3 (last level): [15, 7]
- Level 2: [9, 20]
- Level 1 (root level): [3] The output is the reversed order of these levels.
Example 2:
Input: root = [1]
Visual Representation of the tree: 1
Output: [[1]]
Explanation: The tree has only one level, which is also the root level. The reversed order of a single level is just that level.
Example 3:
Input: root = [] (or null)
Visual Representation of the tree: (empty)
Output: []
Explanation: An empty tree has no nodes, so the traversal result is an empty list.
Constraints
- The number of nodes in the tree is in the range [0, 2000].
- Node values are integers in the range [-1000, 1000].
- The input is a standard binary tree representation (e.g., a pointer to the root node).
Notes
- You will likely need a data structure to keep track of nodes to visit at the current and next levels. A queue is a common choice for level order traversal.
- Consider how you will manage the collection of nodes for each level before reversing them.
- Think about how to handle the case of an empty tree.