给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
样例
样例 1:
输入:{1,2,3}
输出:[[1],[2,3]]
解释:
1
/ \
2 3
它将被序列化为{1,2,3}
层次遍历
样例 2:
输入:{1,#,2,3}
输出:[[1],[2],[3]]
解释:
1
\
2
/
3
它将被序列化为{1,#,2,3}
层次遍历
挑战
挑战1:只使用一个队列去实现它
挑战2:用BFS算法来做
注意事项
- 首个数据为根节点,后面接着是其左儿子和右儿子节点值,"#"表示不存在该子节点。
- 节点数量不超过20。
输入测试数据 (每行一个参数)如何理解测试数据?
/**
* 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: A Tree
* @return: Level order a list of lists of integer
*/
public List<List<Integer>> levelOrder(TreeNode root) {
// write your code here
List<List<Integer>> list =new ArrayList<List<Integer>>();
if (root==null){
return list;
}
Queue<TreeNode> queue =new LinkedList<TreeNode>();
queue.offer(root);
while(!queue.isEmpty()){
ArrayList<Integer> level = new ArrayList();
int size = queue.size(); // 能将同一层的节点放到一个list中的要点
for(int i=0;i<size;i++){
TreeNode temp = queue.poll();;
level.add(temp.val);
if(temp.left !=null)
queue.offer(temp.left);
if(temp.right !=null)
queue.offer(temp.right);
}
list.add(level);
}
return list;
}
}
输入
查看差别
{1,2,3}
输出
[[1],[2,3]]
期望答案
[[1],[2,3]]