:type root: TreeNode :rtype: List[List[int]]
(self, root)
| 38 | |
| 39 | class Solution(object): |
| 40 | def zigzagLevelOrder(self, root): |
| 41 | """ |
| 42 | :type root: TreeNode |
| 43 | :rtype: List[List[int]] |
| 44 | """ |
| 45 | if not root: |
| 46 | return [] |
| 47 | |
| 48 | result = [] |
| 49 | |
| 50 | temp = deque([root]) |
| 51 | next_temp = deque() |
| 52 | _result = [] |
| 53 | LEFT = True |
| 54 | RIGHT = False |
| 55 | currentDirection = LEFT |
| 56 | |
| 57 | while 1: |
| 58 | if temp: |
| 59 | node = temp.popleft() |
| 60 | _result.append(node.val) |
| 61 | |
| 62 | |
| 63 | if node.left: |
| 64 | next_temp.append(node.left) |
| 65 | |
| 66 | if node.right: |
| 67 | next_temp.append(node.right) |
| 68 | |
| 69 | |
| 70 | else: |
| 71 | if currentDirection == LEFT: |
| 72 | result.append(_result) |
| 73 | currentDirection = RIGHT |
| 74 | else: |
| 75 | _result.reverse() |
| 76 | result.append(_result) |
| 77 | currentDirection = LEFT |
| 78 | _result = [] |
| 79 | temp = next_temp |
| 80 | next_temp = deque() |
| 81 | |
| 82 | |
| 83 | if not temp and not next_temp: |
| 84 | if _result: |
| 85 | if currentDirection == LEFT: |
| 86 | result.append(_result) |
| 87 | currentDirection = RIGHT |
| 88 | else: |
| 89 | _result.reverse() |
| 90 | result.append(_result) |
| 91 | |
| 92 | return result |