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