Problem
Given a binary tree, return the bottom-up level order traversal of its nodes’ values.
Examples
Example 1:
3
/ \
9 20
/ \
15 7
Input: root = [3,9,20,null,null,15,7]
Output:[[15,7],[9,20],[3]]
Example 2:
Input: root = [1]
Output:[[1]]
Example 3:
Input: root = []
Output: []
This is follow up of Binary Tree Level Order Traversal - Level by Level
Solution
Method 1 - Use BFS and reverse
We have Idea is to take the level and add to new list.
public List <ArrayList <Integer>> levelOrderBottom(TreeNode root) {
ArrayList <ArrayList<Integer>> result = new ArrayList<ArrayList <>>();
if (root == null) {
return result;
}
LinkedList <TreeNode> current = new LinkedList <TreeNode> ();
LinkedList <TreeNode> next = new LinkedList <TreeNode> ();
current.offer(root);
ArrayList <Integer> numberList = new ArrayList <Integer> ();
// need to track when each level starts
while (!current.isEmpty()) {
TreeNode head = current.poll();
numberList.add(head.val);
if (head.left != null) {
next.offer(head.left);
}
if (head.right != null) {
next.offer(head.right);
}
if (current.isEmpty()) {
current = next;
next = new LinkedList <TreeNode> ();
result.add(numberList);
numberList = new ArrayList <Integer> ();
}
}
//return Collections.reverse(result);
List <List <Integer>> reversedResult = new ArrayList <ArrayList <Integer>> ();
for (int i = result.size() - 1; i>= 0; i--) {
reversedResult.add(result.get(i));
}
return reversedResult;
}