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] ]
思路:还是采用层次遍历的方法,只是始终都将遍历的一层放在结果 List 的头部
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (root == null) return res;
int thislevel = 1;
int nextlevel = 0;
LinkedList<TreeNode> q = new LinkedList<TreeNode>();
q.add(root);
while(q.isEmpty() == false) {
List<Integer> restemp = new ArrayList<Integer>();
while(thislevel > 0) {
TreeNode temp = q.poll();
thislevel--;
restemp.add(temp.val);
if(temp.left != null) {
nextlevel++;
q.offer(temp.left);
}
if(temp.right != null) {
nextlevel++;
q.offer(temp.right);
}
}
res.add(0,restemp);
thislevel = nextlevel;
nextlevel = 0;
}
return res;
}
}