Leetcode 103.二叉树的锯齿形层次遍历

103.二叉树的锯齿形层次遍历

题目

给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
例如:
给定二叉树 [3,9,20,null,null,15,7],

3
/ \
9 20
/ \
15 7
返回锯齿形层次遍历如下:

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

方法

方法1:宽度优先遍历 & dict

Using dic to store the values of each level’s nodes in corresponding lists. When return the result, reverse every other level.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Definition for a binary tree node.
# 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]]
"""
queue=collections.deque([(root,0)]) if root else []
dic=collections.defaultdict(list)
while queue:
node,level=queue.popleft()
dic[level].append(node.val)
if node.left:
queue.append((node.left,level+1))
if node.right:
queue.append((node.right,level+1))
return [dic[level][::(1,-1)[level&1]] for level in range(len(dic))]

方法2:宽度优先遍历 & list

Simple straightforward solution using flag to decide whether from left to right or from right to left

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
# Definition for a binary tree node.
# 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 []

res,tmp,queue,flag=[],[],collections.deque([root]),1
while queue:
for i in range(len(queue)):
node=queue.popleft()
tmp+=[node.val]
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res+=[tmp[::flag]]
tmp=[]
flag*=-1
return res
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root: return []
res, temp, stack, flag=[], [], [root], 1
while stack:
for i in xrange(len(stack)):
node=stack.pop(0)
temp+=[node.val]
if node.left: stack+=[node.left]
if node.right: stack+=[node.right]
res+=[temp[::flag]]
temp=[]
flag*=-1
return res
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
# Definition for a binary tree node.
# 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]]
"""
_r = []
if not root:
return _r

_q = []
_q.append(root)

while _q:
tmp = []

for i in range(len(_q)):
_c = _q.pop(0)
tmp.append(_c.val)

if _c.left:
_q.append(_c.left)
if _c.right:
_q.append(_c.right)

_r.append(tmp)

for index, elem in enumerate(_r):
if index%2:
_r[index].reverse()
return _r