剑指 Offer 32 - III. 从上到下打印二叉树 III

难度中等55
请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。

例如:
给定二叉树: [3,9,20,null,null,15,7],

  1. 3
  2. / \
  3. 9 20
  4. / \
  5. 15 7

返回其层次遍历结果:

  1. [
  2. [3],
  3. [20,9],
  4. [15,7]
  5. ]

Solution

  1. class Solution {
  2. public List<List<Integer>> levelOrder(TreeNode root) {
  3. if ( root == null) return new ArrayList<>();
  4. List<List<Integer>> res = new ArrayList<>();
  5. Stack<TreeNode> left = new Stack<>();
  6. Stack<TreeNode> right = new Stack<>();
  7. left.push(root);
  8. List<Integer> temp = new ArrayList<>();
  9. int cur = 1, next = 0;
  10. boolean trun = true; // 左为 true,右为 false
  11. while (!left.isEmpty() || !right.isEmpty()){
  12. TreeNode node = trun ? left.pop() : right.pop();
  13. temp.add(node.val);
  14. if (!trun){
  15. if (node.right != null){
  16. left.push(node.right);
  17. next ++;
  18. }
  19. if (node.left != null){
  20. left.push(node.left);
  21. next ++;
  22. }
  23. } else {
  24. if (node.left != null){
  25. right.push(node.left);
  26. next ++;
  27. }
  28. if (node.right != null){
  29. right.push(node.right);
  30. next ++;
  31. }
  32. }
  33. if ( --cur == 0){
  34. cur = next;
  35. next = 0;
  36. res.add(temp);
  37. temp = new ArrayList<>();
  38. trun = !trun;
  39. }
  40. }
  41. return res;
  42. }
  43. }