题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
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 ArrayList<ArrayList<Integer> > res = new ArrayList<ArrayList<Integer>>(); if (root == null) { return res; } //采用队列存储每层非空节点,每次循环从队列中取出一层节点处理并将子节点放入队列,直到队列为空 Queue<TreeNode> queue = new ArrayDeque<TreeNode>(); queue.add(root); while (!queue.isEmpty()) { ArrayList<Integer> dataLine = new ArrayList<Integer>(); int n = queue.size(); for (int i = 0; i < n; i++) { TreeNode curNode = queue.poll(); dataLine.add(curNode.val); if (curNode.left != null) { queue.add(curNode.left); } if (curNode.right != null) { queue.add(curNode.right); } } res.add(dataLine); } return res; } } 作者:牛客854832741号 链接:https://www.nowcoder.com/discuss/527524992351858688 来源:牛客网