1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| public class BinaryTreeLevelOrderTraversal { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if (root == null) { return result; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); int crt = 1; int next = 0; List<Integer> list = new ArrayList<Integer>(); while (!queue.isEmpty()) { TreeNode node = queue.poll(); list.add(node.val); crt--; if (node.left != null) { queue.offer(node.left); next++; } if (node.right != null) { queue.offer(node.right); next++; } if (crt == 0) { result.add(new ArrayList<Integer>(list)); list.clear(); crt = next; next = 0; } } return result; } @Test public void test() { TreeNode root = new TreeNode(1); root.left = new TreeNode(2); List<List<Integer>> result = levelOrder(root); } }
|