Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
层序遍历,BFS
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> r = new LinkedList<List<Integer>>();
if(root == null) return r;
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while(!queue.isEmpty() ){
List<Integer> tmp = new ArrayList<Integer>();
LinkedList<TreeNode> list = new LinkedList<TreeNode>();
while(!queue.isEmpty()){
TreeNode t = queue.poll();
tmp.add(t.val);
if(t.left != null){
list.offer(t.left);
}
if(t.right != null){
list.offer(t.right);
}
}
queue = list;
r.add(tmp);
}
return r;
}
- Binary Tree Level Order Traversal II
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> r = new ArrayList<List<Integer>>();
if(root == null) return r;
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while(!queue.isEmpty() ){
List<Integer> tmp = new ArrayList<Integer>();
LinkedList<TreeNode> list = new LinkedList<TreeNode>();
while(!queue.isEmpty()){
TreeNode t = queue.poll();
tmp.add(t.val);
if(t.left != null){
list.offer(t.left);
}
if(t.right != null){
list.offer(t.right);
}
}
queue = list;
r.add(0,tmp); //层序遍历加入顺序倒叙
}
return r;
}
}