public List<List<Integer>> levelOrder(TreeNode root) {
//注意返回类型为List<List<Integer>>型
List<List<Integer>> ret = new LinkedList<>();
if(root == null)
return ret;
//利用队列,类型为LinkedList;Queue中结点的类型为TreeNode
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
List<Integer> list = new LinkedList<>();
int size = queue.size();
while(size>0){ //每一次队列里的元素访问完,为一层
//TreeNode cur = queue.peek();
TreeNode cur = queue.poll(); //poll()也有返回值
list.add(cur.val);
if(cur.left != null)
queue.offer(cur.left);
if(cur.right != null)
queue.offer(cur.right);
//queue.poll();
size--;
}
//每一层的结果list放在一个List中
ret.add(list);
}
return ret;
[二叉树] 层序遍历(返回类型为List<List<Integer>>型)
最新推荐文章于 2024-03-19 11:52:23 发布