Leetcode 103. Binary Tree Zigzag Level Order Traversal

Posted pegasus923

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

 

 

以上是关于Leetcode 103. Binary Tree Zigzag Level Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 103. Binary Tree Zigzag Level Order Traversal

[leetcode tree]103. Binary Tree Zigzag Level Order Traversal

LeetCode103. Binary Tree Zigzag Level Order Traversal 解题报告

[LeetCode]题解(python):103-Binary Tree Zigzag Level Order Traversal

Leetcode 103. Binary Tree Zigzag Level Order Traversal

Leetcode 103. Binary Tree Zigzag Level Order Traversal