Binary Tree Zigzag Level Order Traversal

Question

  1. Given a binary tree, return the zigzag level order traversal of its nodes' values.
  2. (ie, from left to right, then right to left for the next level and alternate between).
  3. Example
  4. Given binary tree {3,9,20,#,#,15,7},
  5. 3
  6. / \
  7. 9 20
  8. / \
  9. 15 7
  10. return its zigzag level order traversal as:
  11. [
  12. [3],
  13. [20,9],
  14. [15,7]
  15. ]

题解1 - 队列

二叉树的广度优先遍历使用队列非常容易实现,这道题要求的是蛇形遍历,我们可以发现奇数行的遍历仍然可以按照广度优先遍历的方式实现,而对于偶数行,只要翻转一下就好了。

Java

  1. /**
  2. * Definition of TreeNode:
  3. * public class TreeNode {
  4. * public int val;
  5. * public TreeNode left, right;
  6. * public TreeNode(int val) {
  7. * this.val = val;
  8. * this.left = this.right = null;
  9. * }
  10. * }
  11. */
  12. public class Solution {
  13. /**
  14. * @param root: The root of binary tree.
  15. * @return: A list of lists of integer include
  16. * the zigzag level order traversal of its nodes' values
  17. */
  18. public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
  19. ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
  20. if (root == null) return result;
  21. boolean odd = true;
  22. Queue<TreeNode> q = new LinkedList<TreeNode>();
  23. q.offer(root);
  24. while (!q.isEmpty()) {
  25. // level traversal
  26. int qLen = q.size();
  27. ArrayList<Integer> level = new ArrayList<Integer>();
  28. for (int i = 0; i < qLen; i++) {
  29. TreeNode node = q.poll();
  30. level.add(node.val);
  31. if (node.left != null) q.offer(node.left);
  32. if (node.right != null) q.offer(node.right);
  33. }
  34. // add level order reverse for even
  35. if (odd) {
  36. result.add(level);
  37. } else {
  38. Collections.reverse(level);
  39. result.add(level);
  40. }
  41. // flip odd and even
  42. odd = !odd;
  43. }
  44. return result;
  45. }
  46. }

源码分析

区分奇数偶数行使用额外变量。

复杂度分析

需要 reverse 的节点数目近似为 n/2, 故时间复杂度 O(n). 最下层节点数目最多 n/2, 故reverse 操作的空间复杂度可近似为 O(n/2).

总的时间复杂度为 O(n), 空间复杂度也为 O(n).

Reference