题目:给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
描述
给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
样例
给一棵二叉树 {3,9,20,#,#,15,7}
:
3
/ \
9 20
/ \
15 7
返回他的分层遍历结果:
[
[3],
[9,20],
[15,7]
]
如果只是遍历的话并不难,但是结果要求是按层次输出每层的数值。
这次做题的一个进步是在没有看示例代码的情况下想到了用List<List>来存放返回的值。难点在于如何将同一层的节点放在一个list当中,最后还是参考了答案。
代码如下:
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 list = new ArrayList();速度要快好多
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;
}
}