Binary Tree Zigzag Level Order Traversal

每次往res里放list的时候,要check一下list是不是空,因为很有可能树遍历完以后,有一个stack是空的,那么对应的list就是空的,空的list不能加到最后的接过去

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example: Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

用两个栈维护正序和反序输出,s1往s2push 的时候,左先进,右后进,这样在遍历s2时,就先遍历后进去的,输出的顺序就是倒着的层序遍历,s2往s1 push的时候,右先进,左后进,这样遍历的时候就是从左到右的正常循序,

2个坑:

  1. 用同一个list的话,往res里传的时候应该deep copy

  2. 往res里传的时候应该保证list不为空,因为两个stack的循环都在一个大循环里,有时候期中一个stack为空

时间复杂度 o(n) , space o(n)

Last updated