Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

102. Binary Tree Level Order Traversal #116

Open
jrmullen opened this issue May 27, 2024 · 0 comments
Open

102. Binary Tree Level Order Traversal #116

jrmullen opened this issue May 27, 2024 · 0 comments

Comments

@jrmullen
Copy link
Owner

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return root

        result = []
        queue = collections.deque()
        queue.append(root)

        # BFS
        while queue:
            level = []
            for _ in range(len(queue)):
                # Pop and add the node's value to the level array
                node = queue.popleft()
                level.append(node.val)

                # Add child nodes to the queue
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            # Once all nodes at a level have been visited, add the the result array
            result.append(level)    
        return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant