题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型ArrayList<ArrayList<>>
*/
public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
// write code here
// write code here
ArrayList<ArrayList<Integer>> list=new ArrayList<>();
TreeNode cursor_1=root;
if(cursor_1==null){
return list;
}
Deque<TreeNode> deque=new LinkedList<>();
deque.push(cursor_1);
int length=1;
while(!deque.isEmpty()){
int num=0;
int nextlength=0;
ArrayList<Integer> sublist=new ArrayList<>();
while(num<length&&(!deque.isEmpty())){
cursor_1=deque.poll();
sublist.add(cursor_1.val);
if(cursor_1.left!=null){
deque.addLast(cursor_1.left);
nextlength++;
}
if(cursor_1.right!=null){
deque.addLast(cursor_1.right);
nextlength++;
}
num++;
}
list.add(sublist);
length=nextlength;
}
return list;
}
}
