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] ]
/**
* 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>> result = new ArrayList<List<Integer>>();
if(root == null){
return result;
}
//当前层有多少node
int currentLevelNodeNum = 1;
//下一层有多少node
int nextLevelNodeNum = 0;
//queue实现层中从左到右的遍历
Queue<TreeNode> queue = new LinkedList<TreeNode>();
//先将root添加到queue中
queue.offer(root);
//当前层还有Node时
while(currentLevelNodeNum != 0){
//当前层的所有Node存放在currentResult中
ArrayList<Integer> currentResult = new ArrayList<Integer>();
//将下一层的node数置为0
nextLevelNodeNum = 0;
//遍历当前层
while(currentLevelNodeNum != 0){
//从queue中取出node
TreeNode node = queue.poll();
//添加到currentResult中
currentResult.add(node.val);
//node数量减一
currentLevelNodeNum--;
//如果有左子树,添加,下一层node数加一
if(node.left != null){
queue.offer(node.left);
nextLevelNodeNum++;
}
//如果有右子树,添加,下一层node数加一
if(node.right != null){
queue.offer(node.right);
nextLevelNodeNum++;
}
}
//当前层的结果添加到总结果中
result.add(0,currentResult);
//遍历下一层
currentLevelNodeNum = nextLevelNodeNum;
}
return result;
}
}
Binary Tree Level Order Traversal I 只要把result.add(0,currentResult)改为result.add(currentResult)即可