Binary Tree Zigzag Traversal

Tree BFS

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

Thought Process

  • We can use a bool variable to denote when we switch directions

Solution

from collections import deque 
class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        if root is None:
            return []
        
        result = []
        queue = deque()
        queue.append(root)
        goLeft = True
        while queue:
            
            levelSize = len(queue)
            currentLevel = deque()
            
            for _ in range(levelSize):
                currentNode = queue.popleft()
                
                if goLeft:
                    currentLevel.append(currentNode.val)
                if not goLeft:
                    currentLevel.appendleft(currentNode.val)
                
                if currentNode.left:
                    queue.append(currentNode.left)
                if currentNode.right:
                    queue.append(currentNode.right)
                    
            result.append(currentLevel)
            goLeft = not goLeft
        return result
                
                
#Depending on the bool variable, we will either append
#normally or in a "push back" fashion

#Time: O(n)
#Space: O(N)

Last updated