题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
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) { // write code here if (root == null) { return new ArrayList<>(); } Queue<TreeNode> que = new LinkedList<>(); ArrayList<ArrayList<Integer>> res = new ArrayList<>(); que.add(root); while(!que.isEmpty()){ int size = que.size(); ArrayList<Integer> tmp = new ArrayList<>(); for(int i = 0;i<size;i++){ TreeNode t = que.remove(); tmp.add(t.val); if(t.left!=null){ que.add(t.left); } if(t.right!=null){ que.add(t.right); } } res.add(tmp); } return res; } }