题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
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 ArrayList<ArrayList<Integer>> result = new ArrayList(); if(root == null){ return result; } Queue<TreeNode> q = new ArrayDeque<TreeNode>(); q.add(root); while(!q.isEmpty()){ ArrayList<Integer> layerList = new ArrayList<>(); int n = q.size(); for(int i = 0;i<n;i++){ TreeNode node =q.poll(); layerList.add(node.val); if(node.left!=null){ q.add(node.left); } if(node.right!=null){ q.add(node.right); } } result.add(layerList); } return result; } }