给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: A Tree * @return: Level order a list of lists of integer */ public List<List<Integer>> levelOrder(TreeNode root) { // write your code here List<List<Integer>> list = new ArrayList<>(); LinkedList<TreeNode> queue = new LinkedList<>(); if (root != null) { queue.offer(root); } while (!queue.isEmpty()) { int len = queue.size(); List<Integer> tmplist = new ArrayList<>(); while (len > 0) { TreeNode treeNode = queue.poll(); tmplist.add(treeNode.val); if (treeNode.left != null) { queue.offer(treeNode.left); } if (treeNode.right != null) { queue.offer(treeNode.right); } len--; } list.add(tmplist); } return list; } }