牛客题霸-求二叉树的层序遍历-Java题解
题目:https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
题解:这道题主要考察的是二叉树的层序遍历,可以使用队列来存储节点,然后每次打印之前计算每一层的节点数,具体可参见代码
java代码实现:
import java.util.*; public class Solution { public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); if(root == null) return res; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while(!queue.isEmpty()){ int size = queue.size();//获取每一层的节点数 ArrayList<Integer> list = new ArrayList<>(); for(int i = 0; i < size; i++){ TreeNode cur = queue.poll(); list.add(cur.val); if(cur.left != null) queue.offer(cur.left); if(cur.right != null) queue.offer(cur.right); } res.add(list); } return res; } }