码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 103. Binary Tree Zigzag Level Order Traversal

时间:2019-07-15 19:55:58      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:tag   play   none   list   trick   one   example   nod   alternate   

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

 

 

Leetcode 103. Binary Tree Zigzag Level Order Traversal

标签:tag   play   none   list   trick   one   example   nod   alternate   

原文地址:https://www.cnblogs.com/pegasus923/p/11190990.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!