Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
Mainly there are two solutions:1. using BFS, add the current level as the first of the result list
2. DFS reverse the lists at last
Solution2 DFS
2ms 81.61
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> lists = new ArrayList<List<Integer>>();
if(root == null){
return lists;
}
getOrder(root, lists, 0);
Collections.reverse(lists);
return lists;
}
public void getOrder(TreeNode root, List<List<Integer>> lists, int level){
if(root == null){
return;
}
List<Integer> list;
if(lists.size() == level){
list = new ArrayList<Integer>();
lists.add(list);
}else{
list = lists.get(level);
}
list.add(root.val);
if(root.left != null){
getOrder(root.left, lists, level + 1);
}
if(root.right != null){
getOrder(root.right, lists, level + 1);
}
}
}