102. 二叉树的层序遍历
很巧妙的,又学习了一种层次遍历的方法,就是说根据当前的队列的长度去遍历,遍历的当前队列的长度就是该层次的节点个数。
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public List<List<Integer>> levelOrder(TreeNode root) {List<List<Integer>> levelOrderList = new ArrayList<>();if(root == null) return levelOrderList;Queue<TreeNode> queue = new LinkedList<>(); //用于做队列,遍历整棵树List<Integer> list = new ArrayList<>(); // 用于存储用队列遍历树的valqueue.add(root);while(queue.size()!=0) {// System.out.println("当前队列的长度" + queue.size());int l = queue.size();for(int i=0;i<l; i++) {TreeNode front = queue.poll(); //LinkedList的poll方法可以取出第一个元素的值。list.add(front.val);if(front.left!=null) queue.add(front.left);if(front.right!=null) queue.add(front.right);}
/* System.out.print("当前放入的元素为");Iterator iterator = list.iterator();while(iterator.hasNext()){System.out.print(iterator.next() + " ");}System.out.println(); */levelOrderList.add(list);list = new ArrayList<Integer>();}return levelOrderList;}
}