🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line
\uD83D\uDD34 Check out LeetCode The Hard Way for more solution explanations and tutorials. \n\uD83D\uDFE0 Check out our Discord Study Group for live discussion.
\uD83D\uDD34 Check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \n\uD83D\uDFE0 Check out our [Discord Study Group](https://discord.gg/Nqm4jJcyBf) for live discussion.\n\uD83D\uDFE2 Give a star on [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post if you like it.\n\uD83D\uDD35 Check out [Screencast](https://www.youtube.com/watch?v=SDFFhfwEIiY&list=PLBu4Bche1aEU-8z7xl3-B9lfw_DJtT_xs&index=19) if you are interested.\n\n---\n\n```py\n# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    # Level traversal -> BFS\n    # reverse the list for odd-index level\n    def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n        # if there is no root, then return []\n        if not root: return []\n        # init ans and queue with initial node `root`\n        ans, q = [], [root]\n        # BFS\n        while q:\n            # direction - 1 for even-index level and -1 for odd-index level\n            d = -1 if len(ans) % 2 == 1 else 1\n            # put all node values to a list with the correct direction \n            # and add to `ans` \n            ans.append([n.val for n in q][::d])\n            # for each node in the queue, \n            # we add the left or right node to the queue if applicable\n            q = [n for node in q for n in (node.left, node.right) if n]\n        return ans\n```
['Breadth-First Search', 'Python']