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,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
想着用之前顺序的方法,但是List在add的时候用栈来存放,然后再pop出来就逆序了。
public List<List<Integer>> levelOrder1(TreeNode root) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
if (root == null)
return list;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
Stack<List<Integer>> stack = new Stack<List<Integer>>();
queue.add(root);
while (!queue.isEmpty()) {
List<Integer> list1 = new ArrayList<Integer>();
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode t1 = queue.poll();
list1.add(t1.val);
if (t1.left != null)
queue.add(t1.left);
if (t1.right != null)
queue.add(t1.right);
}
//list.add(list1);
stack.push(list1);
}
while (!stack.isEmpty()) {
list.add(stack.pop());
}
return list;
}
也是一次就通过了,再去看看别人的代码。
public class Solution {
/**
* @param root: The root of binary tree.
* @return: buttom-up level order a list of lists of integer
*/
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
ArrayList<Integer> level = new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode head = queue.poll();
level.add(head.val);
if (head.left != null) {
queue.offer(head.left);
}
if (head.right != null) {
queue.offer(head.right);
}
}
result.add(level);
}
Collections.reverse(result);
return result;
}
}
最后用系统自带的reverse方法逆转也是可行的。