➜ ~

Playing Hacks and Stuffs!


Project maintained by h4ckyou Hosted on GitHub Pages — Theme by mattgraham

Binary Tree Level Order Traversal

image image

Given the root of a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).

To solve this we can use a breadth-first search (BFS) approach to traverse the binary tree level by level

One each level of our traverse we use a queue to keep track of nodes. While the queue is not empty, we process nodes at each level and add their values to the level_values list.

After processing all nodes at the current level, we append level_values to the result list.

Here’s more to it link

Here’s the solve script: link image

Leetcode Submission Script

from collections import deque

class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []

        result = []
        queue = deque([root])

        while queue:
            level_values = []
            level_size = len(queue)

            for _ in range(level_size):
                node = queue.popleft()
                level_values.append(node.val)

                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)

            result.append(level_values)

        return result