層序遍歷的思路:若樹爲空,則返回空,不然從樹的第一層開始,即從根節點,從上而下逐層遍歷。java
從上到下,從左到右打印二叉樹,返回一維數組int[] res
。node
class Solution { public int[] levelOrder(TreeNode root) { if (root == null) return new int[0]; Queue<TreeNode> q = new LinkedList<>(); q.add(root); List<Integer> list = new ArrayList<>(); while (!q.isEmpty()) { TreeNode node = q.poll(); list.add(node.val); if (node.left != null) q.add(node.left); if (node.right != null) q.add(node.right); } int[] res = new int[list.size()]; for (int i = 0; i < res.length; i++) res[i] = list.get(i); return res; } }
從上到下,從左到右打印二叉樹,返回List<List<Integer>> res
。數組
class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); Queue<TreeNode> q = new LinkedList<>(); if (root != null) q.add(root); while (!q.isEmpty()) { List<Integer> list = new ArrayList<>(); for (int i = q.size(); i > 0; i--) { TreeNode node = q.poll(); list.add(node.val); if (node.left != null) q.add(node.left); if (node.right != null) q.add(node.right); } res.add(list); } return res; } }
從上到下,按zigzag方式打印(即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行),返回List<List<Integer>> res
。code
class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); Queue<TreeNode> q = new LinkedList<>(); if (root != null) q.add(root); while (!q.isEmpty()) { LinkedList<Integer> list = new LinkedList<>(); for (int i = q.size(); i > 0; i--) { TreeNode node = q.poll(); if (res.size() % 2 == 0) list.addLast(node.val); else list.addFirst(node.val); if (node.left != null) q.add(node.left); if (node.right != null) q.add(node.right); } res.add(list); } return res; } }
從下到上,從左到右打印二叉樹,返回List<List<Integer>> res
。leetcode
class Solution { public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); Queue<TreeNode> q = new LinkedList<>(); if (root != null) q.add(root); while (!q.isEmpty()) { List<Integer> list = new ArrayList<>(); for (int i = q.size(); i > 0; i--) { TreeNode node = q.poll(); list.add(node.val); if (node.left != null) q.add(node.left); if (node.right != null) q.add(node.right); } // 頭插法 res.add(0, list); } return res; } }