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] ]
代码我直接照着Binary Tree Level Order Traversal I 改的
就是将最后的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) {
LinkedList<List<Integer>> tmp = new LinkedList<List<Integer>>();
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(root == null)
return res;
List<TreeNode> currlayer= new ArrayList<TreeNode>();
currlayer.add(root);
while(!currlayer.isEmpty()){
List<TreeNode> nextlayer = new ArrayList<TreeNode>();
List<Integer> currvalue = new ArrayList<Integer>();
for(TreeNode node : currlayer){
currvalue.add(node.val);
if(node.left != null)
nextlayer.add(node.left);
if(node.right != null)
nextlayer.add(node.right);
}
tmp.add(currvalue);
currlayer = nextlayer;
}
while(!tmp.isEmpty()){
List<Integer> list = tmp.removeLast();
res.add(list);
}
return res;
}
}