借助队列来实现,先将root存入队列,然后取出root,将root的左右子节点加入队列,每次取值要把队列内的数据全部取完就代表这一层遍历完了,将每个节点的左右子节点加入队列中
public class Test102 {
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public List<List<Integer>> levelOrder(TreeNode root) {
if(root==null) {
return new ArrayList<List<Integer>>();
}
List<List<Integer>> result = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
int curQueueSize = queue.size();
List<Integer> levelList = new ArrayList<>();
for(int i=0; i<curQueueSize; i++) {
TreeNode node = queue.poll();
levelList.add(node.val);
if(node.left!=null) {
queue.offer(node.left);
}
if(node.right!=null) {
queue.offer(node.right);
}
}
result.add(levelList);
}
return result;
}
}