leetcode: 103. Binary Tree Zigzag Level Order Traversal

Difficulty

Medium.

Problem

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

AC

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None


# BFS
class Solution():
    def zigzagLevelOrder(self, root):
        res = []
        if root:
            level = [root]
            while len(level):
                q = [node.val for node in level]
                if len(res) % 2:
                    res.append(q[::-1])
                else:
                    res.append(q)
                tmp = []
                for node in level:
                    if node.left:
                        tmp.append(node.left)
                    if node.right:
                        tmp.append(node.right)
                level = tmp
        return res

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券