-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzigzagLevelOrder.py
42 lines (40 loc) · 1.22 KB
/
zigzagLevelOrder.py
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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @return {integer[][]}
def zigzagLevelOrder(self, root):
result = []
if root == None:
return result
stack = []
stack.append(root)
result.append([root.val])
i = 1
while(len(stack) != 0):
node = stack.pop()
row = []
while(node != None):
if i%2: #right to left
if node.right != None:
row.append(node.right)
if node.left != None:
row.append(node.left)
else:
if node.left != None:
row.append(node.left)
if node.right != None:
row.append(node.right)
if len(stack) == 0:
break
else:
node = stack.pop()
if len(row) != 0:
result.append([n.val for n in row])
stack = row
i+=1
return result