LeetCode 103 Binary Tree Zigzag Level Order Traversal

LeetCode 103 Binary Tree Zigzag Level Order Traversal Problem

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

class Solution(object):
    def zigzagLevelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        # level order
        if root is None:
            return []
        q = [[root]]
        for level in q:
            record = []
            for node in level:
                if node.left:
                    record.append(node.left)
                if node.right:
                    record.append(node.right)
            if record:
                q.append(record)
        # zigzag order
        res = []
        for index, level in enumerate(q):
            temp = [x.val for x in level]
            if index % 2 == 0:
                res.append(temp)
            else:
                res.append(temp[::-1])
        return res
Download Binary Tree Zigzag Level Order Traversal.py

List of all Binary Tree Zigzag Level Order Traversal problems

Leetcode 103 Binary Tree Zigzag Level Order Traversal problem solution in python3 with explanation. This is the best place to expand your knowledge and get prepared for your next interview.

self.val = x

Feedback is the most important part of any website.

If you have any query, suggestion or feedback, Please feel free to contact us.