Leetcode 103. Binary Tree Zigzag Level Order Traversal

https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/

Medium

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).

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]
]


  • 类似BFS,一层层扩展。先从左到右把node放到list里,再判断是否需要反转。
 1 # Definition for a binary tree node.
 2 # class TreeNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution:    
 9     def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
10         if root is None:
11             return []
12         
13         res = []
14         cur = [root]
15         from_right = False
16         
17         while cur:
18             next_level, vals = [], []
19             
20             for node in cur:
21                 vals.append(node.val)
22                 
23                 if node.left:
24                     next_level.append(node.left)
25 
26                 if node.right:
27                     next_level.append(node.right)
28                     
29             res.append(vals[::-1] if from_right else vals) # trick
30             from_right = not from_right
31             
32             cur = next_level
33         
34         return res        
View Python Code

 

 

posted on 2019-07-15 19:43  浩然119  阅读(183)  评论(0编辑  收藏  举报