给定一个二叉树,返回该二叉树层序遍历的结果,(从左到右,一层一层地遍历)
求二叉树的层序遍历
http://www.nowcoder.com/questionTerminal/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 if (root == null) { return new ArrayList<ArrayList<Integer>>(); } ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); // 每一层以null结尾 queue.offer(null); // 遍历到最后一层时,只剩下null while (!queue.isEmpty() && queue.peek() != null) { ArrayList<Integer> r = new ArrayList<>(); while (queue.peek() != null) { TreeNode t = queue.poll(); r.add(t.val); if (t.left != null) { queue.offer(t.left); } if (t.right != null) { queue.offer(t.right); } } // 需要弹出上一层队尾的null queue.poll(); queue.offer(null); res.add(r); } return res; } }