Skip to content

Commit aad36a6

Browse files
committed
2018.12.06 LeetCode 103
1 parent decf90f commit aad36a6

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

2018.12.06-leetcode103/Despacito.md

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# LeetCode 103 Binary Tree Zigzag Level Order Traversal
2+
## 1. Description
3+
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).
4+
5+
For example:
6+
Given binary tree [3,9,20,null,null,15,7],
7+
8+
3
9+
/ \
10+
9 20
11+
/ \
12+
15 7
13+
14+
return its zigzag level order traversal as:
15+
```python
16+
[
17+
[3],
18+
[20,9],
19+
[15,7]
20+
]
21+
```
22+
## 2. Solution
23+
```python
24+
# Definition for a binary tree node.
25+
# class TreeNode:
26+
# def __init__(self, x):
27+
# self.val = x
28+
# self.left = None
29+
# self.right = None
30+
31+
class Solution:
32+
def zigzagLevelOrder(self, root):
33+
"""
34+
:type root: TreeNode
35+
:rtype: List[List[int]]
36+
"""
37+
if not root:
38+
return []
39+
l = [root, '#']
40+
result = []
41+
level = []
42+
flag = 1
43+
while len(l) > 1:
44+
curr = l.pop(0)
45+
if curr != '#':
46+
if flag == 1:
47+
level.append(curr.val)
48+
else:
49+
level.insert(0, curr.val)
50+
if curr.left:
51+
l.append(curr.left)
52+
if curr.right:
53+
l.append(curr.right)
54+
else:
55+
l.append('#')
56+
result.append(level)
57+
level = []
58+
flag *= -1
59+
result.append(level)
60+
return result
61+
```

0 commit comments

Comments
 (0)