MCPcopy Index your code
hub / github.com/HuberTRoy/leetCode / zigzagLevelOrder

Method zigzagLevelOrder

BFS/BinaryTreeZigzagLevelOrderTraversal.py:40–92  ·  view source on GitHub ↗

:type root: TreeNode :rtype: List[List[int]]

(self, root)

Source from the content-addressed store, hash-verified

38
39class 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

Callers

nothing calls this directly

Calls 1

reverseMethod · 0.80

Tested by

no test coverage detected