Q:
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]
]
Analysis:
使用队列,采用BFS,从根结点自上而下遍历,最终将存储的链表翻转。
Code:
/**
* 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>> list = new LinkedList<List<Integer>>();
//用队列去保存遍历树的每层的结点,遍历完一层,该层上的元素会出队
Queue<TreeNode> queue = new LinkedList<TreeNode>();
//处理空树情况
if (root == null) {
return list;
}
queue.offer(root);
while (!queue.isEmpty()) {
//获取树每层的队列中结点的个数
int size = queue.size();
//将每树每层队列中结点存储在链表中
List<Integer> level=new LinkedList<>();
while (size > 0) {
//先遍历左子树
if (queue.peek().left != null) {
queue.offer(queue.peek().left);
}
//再遍历右子树
if (queue.peek().right != null) {
queue.offer(queue.peek().right);
}
//进行每层结点的链表添加,每次取出队首元素
level.add(queue.poll().val);
size--;
}
//将树的每层结点的链表添加至要返回的"父链表"中
list.add(level);
}
//翻转链表
Collections.reverse(list);
return list;
}
}
Des:
Queue方法说明
(来自http://www.cnblogs.com/end/archive/2012/10/25/2738493.html):
add 增加一个元索 如果队列已满,则抛出一个IIIegaISlabEepeplian异常
remove 移除并返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
element 返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
offer 添加一个元素并返回true 如果队列已满,则返回false
poll 移除并返问队列头部的元素 如果队列为空,则返回null
peek 返回队列头部的元素 如果队列为空,则返回null
put 添加一个元素 如果队列满,则阻塞
take 移除并返回队列头部的元素 如果队列为空,则阻塞