Binary Tree Zigzag Level Order Traversal

Problem: Binary Tree Zigzag Level Order Traversal

The problem can be solved by breadth-first-tree, and we can use a switching variable to implement zigzag.

Code in Python:

# 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 not root: return []
        ans = []
        currentLevel, direction = [root], 1
        while currentLevel:
            nextLevel = []
            for node in currentLevel:
                if node.left: nextLevel.append(node.left)
                if node.right: nextLevel.append(node.right)
            ans.append([node.val for node in currentLevel[::direction]])
            direction = -direction
            currentLevel = nextLevel
        return ans

results matching ""

    No results matching ""