LeetCode: [103] 二叉树的锯齿形层序遍历

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
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):

def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res = []
if root is None:
return res
if root.left is None and root.right is None:
res.append([root.val])
return res

height = self.height(root)
nodelist = [root]
for i in range(0, height):
subnodelist = []
subres = []
while nodelist:
cur = nodelist.pop(0)
subres.append(cur.val)
if cur.left:
subnodelist.append(cur.left)
if cur.right:
subnodelist.append(cur.right)

nodelist = subnodelist
if i % 2 != 0:
subres.reverse()
res.append(subres)

return res

def height(self, tree):
if tree is None:
return 0
else:
return 1 + max(self.height(tree.left), self.height(tree.right))