Binary Tree Level Order Traversal
http://www.lintcode.com/problem/binary-tree-level-order-traversal
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
Example Given binary tree {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
Challenge: Using only 1 queue to implement it.
Solution: 参考九章答案,BFS模板级解法!
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: Level order a list of lists of integer
*/
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
// write your code here
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>> ();
if(root==null){
return res;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
TreeNode temp = new TreeNode(0);
while(!queue.isEmpty()){
ArrayList<Integer> level = new ArrayList<Integer>();
int size = queue.size();
for(int i = 0; i < size; i++){
temp = queue.poll();
level.add(temp.val);
if(temp.left!=null){
queue.offer(temp.left);
}
if(temp.right!=null){
queue.offer(temp.right);
}
}
res.add(level);
}
return res;
}
}