바위타는 두루미
[leetcode]103. Binary Tree Zigzag Level Order Traversal 본문
728x90
103. Binary Tree Zigzag Level Order Traversal
Given a binary tree, return the zigzag level ordertraversal 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] ]
class Solution(object):
def zigzagLevelOrder(self, root):
level = 0
result = []
parents = []
currents = []
if root :
currents.append(root)
while currents:
tmp =[]
parents = currents
currents = []
for p in parents:
tmp.append(p.val)
if p.left :
currents.append(p.left)
if p.right :
currents.append(p.right)
result.append(tmp if level %2 ==0 else tmp[::-1] )
level +=1
return result
'Study > Algorithm' 카테고리의 다른 글
[leetcode]116. Populating Next Right Pointers in Each Node (0) | 2019.08.09 |
---|---|
[leetcode]105. Construct Binary Tree from Preorder and Inorder Traversal (0) | 2019.08.09 |
[leetcode]94. Binary Tree Inorder Traversal (0) | 2019.08.09 |
[leetcode]160. Intersection of Two Linked Lists (1) | 2019.08.08 |
[leetcode] 2. add two numbers (0) | 2019.08.07 |
Comments