Offer.P32-III[从上到下打印二叉树III]
方法一:层序遍历
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
|
class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> ans = new ArrayList<>(); Deque<TreeNode> queue = new ArrayDeque<>(); if (root != null) queue.offer(root); boolean flag = false; while (!queue.isEmpty()) { int size = queue.size(); List<Integer> list = new ArrayList(); while (size-- > 0) { TreeNode cur = queue.poll(); if (cur.left != null) queue.offer(cur.left); if (cur.right != null) queue.offer(cur.right); list.add(cur.val); } if (flag) Collections.reverse(list); ans.add(list); flag = !flag; } return ans; } }
|
- 时间复杂度:$O(n)$
- 空间复杂度:$O(n)$