题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型ArrayList<ArrayList<>> */ public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) { //层次遍历,使用队列 ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); Queue<TreeNode> q = new ArrayDeque<TreeNode>(); if(root == null) return list; q.add(root); while(!q.isEmpty()){ //该列表用来存储每一层数据 ArrayList<Integer> list_1 = new ArrayList<Integer>(); //提前取队列长度,不能直接q.size()放进for int n = q.size(); for(int i = 0; i < n; i++){ TreeNode t = q.poll(); list_1.add(t.val); if(t.left != null) q.add(t.left); if(t.right != null) q.add(t.right); } //将一层数据放进list list.add(list_1); } return list; } }