Leetcode 103. Binary Tree Zigzag Level Order Traversal

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

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

For example:
Given binary tree [3,9,20,null,null,15,7],app

    3
   / \
  9  20
    /  \
   15   7

 

return its zigzag level order traversal as:ide

[
  [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
相關文章
相關標籤/搜索