-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem103.py
More file actions
76 lines (62 loc) · 1.5 KB
/
problem103.py
File metadata and controls
76 lines (62 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
'''
103. Binary Tree Zigzag Level Order Traversal
Medium
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]
]
Solution:
Remember, how the node is popped out of the stack is the same, the only different is
which direction that every iteration by finding out how many members are in rst.
In order to change direction, only use [::-1] as the method to reverse the list.
'''
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
from collections import deque
stack = deque([root])
rst = []
while stack:
tmp = []
nextStack = deque([])
while stack:
node = stack.popleft()
tmp.append(node.val)
if node.left:
nextStack.append(node.left)
if node.right:
nextStack.append(node.right)
if len(rst) % 2 == 0:
rst.append(tmp)
else:
rst.append(tmp[::-1])
stack = nextStack
return rst
if __name__ == '__main__':
s = Solution()
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.right.right = TreeNode(5)
print s.zigzagLevelOrder(root)