Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
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]
]

My 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]]
        """
        if root==None:
            return []
        search_list=[root]
        read_label=True
        record_list=[]
        while search_list:
            tmp_record=[]
            will_search=[]
            for item in search_list:
                left=item.left
                if left!=None:
                    will_search.append(left)
                right=item.right
                if right!=None:
                    will_search.append(right)
                tmp_record.append(item.val)
            if not read_label:
                tmp_record.reverse()
            search_list=will_search
            record_list.append(tmp_record)
            read_label=not read_label
        return record_list
                

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