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] ]
看起来好像和一般的level order traversal没什么区别,就是把结果倒过来就行了。这里用了一个ArrayList<Integer> previousLevel来记录前一层的Node们。
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
//the helper array that stores all the nodes of the previous level
ArrayList<TreeNode> previousLevel;
LinkedList<List<Integer>> result = new LinkedList<List<Integer>>();
if(root == null){
return result;
}
else{
previousLevel = new ArrayList<TreeNode>();
previousLevel.add(root);
}
while(!previousLevel.isEmpty()){
LinkedList<Integer> thisLevel = new LinkedList<Integer>();
ArrayList<TreeNode> temp = new ArrayList<TreeNode>();
for(TreeNode node : previousLevel){
thisLevel.add(node.val);
if(node.left != null)
temp.add(node.left);
if(node.right != null)
temp.add(node.right);
}
previousLevel = temp;
result.addFirst(thisLevel);
}
return result;
}
}