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] ]这道题除了能想到把I的结果逆置然后输出之外,没有想到其他的好办法
代码如下
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (root == null)
return result;
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
ArrayList<Integer> value = new ArrayList<Integer>();
queue.add(root);
int remainNum = 1;
int curNum = 0;
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
value.add(cur.val);
remainNum--;
if (cur.left != null) {
queue.add(cur.left);
curNum++;
}
if (cur.right != null) {
queue.add(cur.right);
curNum++;
}
if (remainNum == 0) {
remainNum = curNum;
curNum = 0;
result.add(value);
value = new ArrayList<Integer>();
}
}
Collections.reverse(result);
return result;
}