标签:
Given a binary tree, return the level order traversal of its nodes‘ values. (ie, from left to right, level by level).
For 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] ]
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
Subscribe to see which companies asked this question
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public List<List<Integer>> levelOrder(TreeNode root) { 12 List<List<Integer>> res = new ArrayList<List<Integer>>(); 13 Queue<TreeNode> q = new LinkedList<TreeNode>(); 14 if(root == null) return res; 15 q.add(root); 16 while(!q.isEmpty()){ 17 List<Integer> tmp = new ArrayList<Integer>(); 18 int size = q.size(); 19 for(int i = 0; i< size; i++){ 20 TreeNode node = q.poll(); 21 tmp.add(node.val); 22 if(node.left != null) q.add(node.left); 23 if(node.right != null) q.add(node.right); 24 } 25 res.add(tmp); 26 27 } 28 return res; 29 } 30 }
java 中queue 的操作:
add 增加一个元索 如果队列已满,则抛出一个IIIegaISlabEepeplian异常
remove 移除并返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
element 返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
offer 添加一个元素并返回true 如果队列已满,则返回false
poll 移除并返问队列头部的元素 如果队列为空,则返回null
peek 返回队列头部的元素 如果队列为空,则返回null
put 添加一个元素 如果队列满,则阻塞
take 移除并返回队列头部的元素 如果队列为空,则阻
102. Binary Tree Level Order Traversal Java Solutions
标签:
原文地址:http://www.cnblogs.com/guoguolan/p/5452617.html