|
| 1 | +""" |
| 2 | +102. Binary Tree Level Order Traversal |
| 3 | +https://leetcode.com/problems/binary-tree-level-order-traversal/ |
| 4 | +""" |
| 5 | + |
| 6 | +from typing import List, Optional |
| 7 | + |
| 8 | + |
| 9 | +# Definition for a binary tree node. |
| 10 | +class TreeNode: |
| 11 | + def __init__(self, val=0, left=None, right=None): |
| 12 | + self.val = val |
| 13 | + self.left = left |
| 14 | + self.right = right |
| 15 | + |
| 16 | + |
| 17 | +""" |
| 18 | +Solution |
| 19 | + Breadth First Search (BFS) using Queue |
| 20 | +
|
| 21 | + The problem is asking to return the node values at each level of the binary tree. |
| 22 | + To solve this problem, we can use BFS algorithm with a queue. |
| 23 | + We will traverse the tree level by level and store the node values at each level. |
| 24 | +
|
| 25 | + 1. Initialize an empty list to store the output. |
| 26 | + 2. Initialize an empty queue. |
| 27 | + 3. Add the root node to the queue. |
| 28 | + 4. While the queue is not empty, do the following: |
| 29 | + - Get the size of the queue to know the number of nodes at the current level. |
| 30 | + - Initialize an empty list to store the node values at the current level. |
| 31 | + - Traverse the nodes at the current level and add the node values to the list. |
| 32 | + - If the node has left or right child, add them to the queue. |
| 33 | + - Decrease the level size by 1. |
| 34 | + - Add the list of node values at the current level to the output. |
| 35 | + 5. Return the output. |
| 36 | +
|
| 37 | +Time complexity: O(N) |
| 38 | + - We visit each node once |
| 39 | +
|
| 40 | +Space complexity: O(N) |
| 41 | + - The maximum number of nodes in the queue is the number of nodes at the last level |
| 42 | + - The maximum number of nodes at the last level is N/2 |
| 43 | + - The output list stores the node values at each level which is N |
| 44 | + - Thus, the space complexity is O(N) |
| 45 | +
|
| 46 | +""" |
| 47 | + |
| 48 | + |
| 49 | +class Solution: |
| 50 | + def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: |
| 51 | + if root is None: |
| 52 | + return |
| 53 | + output = [] |
| 54 | + queue = [] |
| 55 | + queue.append(root) |
| 56 | + |
| 57 | + while len(queue) > 0: |
| 58 | + level_size = len(queue) |
| 59 | + level_output = [] |
| 60 | + |
| 61 | + while level_size > 0: |
| 62 | + node = queue.pop(0) |
| 63 | + level_output.append(node.val) |
| 64 | + |
| 65 | + if node.left is not None: |
| 66 | + queue.append(node.left) |
| 67 | + if node.right is not None: |
| 68 | + queue.append(node.right) |
| 69 | + |
| 70 | + level_size -= 1 |
| 71 | + |
| 72 | + output.append(level_output) |
| 73 | + |
| 74 | + return output |
0 commit comments